How to initialize tom-select with htmx ?

Introduction

I would like to initialize a select element like in the tom-select Example with my own method:

<select id="select-repo" placeholder="Pick a repository..." multiple></select>

function my_select_init(el) {
  new TomSelect(el, {
    persist: false,
    createOnBlur: true,
    create: true
  })
}

There two different ways:

Case 1: The full page gets loaded

In this case you can use one of the modern onLoad methods.

For example:

document.addEventListener('DOMContentLoaded', function () {
  // do something here ...
}, false);

Case 2: the fragment get inserted into the DOM via htmx

How to initialize the snippet ?

Preferred solution

I want the HTML and the on-load code to be in one place ( Locality of Behaviour ) and I want this html fragment to be the same for both cases.

Up to now I don’t use Hyperscript or Alpine.js, but I am open to use one of these libraries, if this makes the solution simpler.

Answer by Carson ( https://fediverse.org/htmx_org )

What you want to use is the htmx.onLoad callback:

htmx.onLoad(function(elt) {
  // look up all elements with the tomselect class on it within the element
  var allSelects = htmx.findAll(elt, ".tomselect")
  for( select of allSelects ) {
    new TomSelect(select, {
                  persist: false,
                  createOnBlur: true,
                  create: true
                 });
  }
}

This javascript will execute initially when the page is loaded on the body element, and then for all new content added by htmx to the page.

See https://htmx.org/docs/#3rd-party