Selectable
Install
npm
npm install selectable.js --save
Bower
bower install selectable.js --save
Browser
Grab the file from one of the CDNs and include it in your page:
https://unpkg.com/selectable.js@latest/selectable.min.js
or
https://cdn.jsdelivr.net/npm/selectable.js@latest/selectable.min.js
You can replace latest with the required release number if needed.
Initialise
This will create a new instance and add any element found in the DOM with the ui-selectable
class name and make them selectable.
const selectable = new Selectable();
If you don't add the "ui-selectable" class name to your items then simply tell the instance what to look for instead with the filter option:
const selectable = new Selectable({
filter: ".my-classname"
});
// or
const selectable = new Selectable({
filter: document.querySelectorAll(".my-classname")
});
If your document doesn't have any selectable items yet, e.g. they're added asynchronously via an ajax call, then simply create a new instance as normal, then use the add()
method when they're available:
const selectable = new Selectable();
// items added to DOM ...
// then...
selectable.add(items);
Multiple Instances
It's important to note that multiple instances of `Selectable` on one page can conflict with each other if no container is defined with the `appendTo` option.
The problem is that the event listeners for an instance (mousedown
/ touchstart
and mouseup
/ touchend
) are attached to the appendTo
element. If you have more than one instance and don't define a container, it defaults to document.body
so for example you'll have multiple mousedown
event listeners attached to document.body
and they'll all fire at the same time and hence all selectable.start
and selectable.end
events for each instance defined with on()
will fire at same time.
By defining a unique container for each instance with appendTo
, the event listeners are instead attached to that container and will prevent conflicting with other instances.
<ul id="items1">
<li class="item">1</li>
<li class="item">2</li>
<li class="item">3</li>
<li class="item">4</li>
...
</ul>
<ul id="items2">
<li class="item">1</li>
<li class="item">2</li>
<li class="item">3</li>
<li class="item">4</li>
...
</ul>
const list1 = document.getElementById("items1");
const list2 = document.getElementById("items2");
const selectable1 = new Selectable({
filter: list1.children,
appendTo: list1
});
const selectable2 = new Selectable({
filter: list2.children,
appendTo: list2
});
Retrieving Instance
If you didn't attach the instance to a variable then you can retrieve it by accessing the _selectable
property on the element defined by the appendTo
option:
// Define parent
const parent = document.getElementById("items");
// Instantiate
new Selectable({
appendTo: parent
});
// Retrieve instance
const instance = parent._selectable;
If you didn't define an element with appendTo
, then you can retrieve it with document.body._selectable
.