Usage

To use the selectable elements behavior you need to include the file selectableelements.js like this:

<script type="text/javascript" src="js/selectableelements.js"></script>

You also need to define what you want selected elements to look like. This is done by defining a CSS rule for the class selected.

<style type="text/css">

.selected {
   background: Highlight;
   color:      HighlightText;
}

</style>

After this you need to define the HTML that you want to describe your data. In this case we'll keep it simple and use a DIV as a container with DIV elements as items.

<div id="div-1">
   <div>Item 0</div>
   <div>Item 1</div>
   <div>Item 2</div>
   <div>Item 3</div>
   <div>Item 4</div>
</div>

Once the HTML element is defined we can add the behavior (there is no need to wait until the entire page with images has loaded). This is done by creating a new JavaScript object from the SelectableElements class. In this case we want to allow multiple selection so we pass true as the second argument.

<script type="text/javascript">

var se = new SelectableElements(document.getElementById("div-1"), true);
se.onchange = function () {
	window.status = se.getSelectedIndexes();
};

</script>

The code above also shows how to get a callback once the user changes the selected items.

Result

Using the code from above with a few more CSS rules set up we get.

Item 0
Item 1
Item 2
Item 3
Item 4

Disable Selection

It is also a good idea to disable selection since ctrl click and shift click will select text by default.

To disable the selection in IE we add an event listener that listens for the selectionstart event and when it is fired we return false to disable the default behavior.

<div id="div-1" onselectstart="return false">

The Mozilla solution is simply put just beautiful. To disable selection one uses the CSS property -moz-user-select (part of CSS3 proposal) and set the value to none.

#div-1 {
   -moz-user-select: none;
}

Introduction
Usage
Sub Classes
API
Demo
Download

Author: Erik Arvidsson