In my last post I discussed how to use dojo and CSS classes to create a user-selectable set of HTML elements. The example provided a list-like single-selection interface that allowed the user to only select single elements.
Today, I am going to expand upon that example to create a multiple-select interface allowing the user to control-click or shift-click to select multiple elements.
We are going to start off right where we left off last time, by modifying the focusObject() function we previously definded. The function is going to be a bit more involved as we need to check for 4 mouse states (click, control click, shift click, and control shift click). Let's start the update by redefining the parameters to our function. If you remember, our previous function template was as follows
function focusObject(class,objId) { }
We're going to change this template to include a new parameter "e" which will be the first argument that the event handler in non-IE browsers receives, or for IE browsers, the event object. So, redefined, our function template now looks like this:
function focusObject(class,objId,e) { }
The e parameter holds the two boolean properties ctrlKey and shiftKey which tells us the state of the keys at the time the click ocurred. Quite simply, if they are true, the appropriate key was pressed. So, lets expand our function a litle bit, and create a statement that will check for each of the four conditions we need to check. Also, because we are going to refer to the HTML node the user selected quite frequently, lets go ahead and capture that node to a variable right from the start.
function focusObject(class,objId,e) {
// Capture the selected node...
var selNode = dojo.byId(objId);
// JUST CLICK
if ((!e.ctrlKey) && (!e.shiftKey)) {
// CONTROL SHIFT CLICK
} else if ((e.ctrlKey) && (e.shiftKey)) {
// CONTROL CLICK
} else if (e.ctrlKey) {
// SHIFT CLICK
} else if (e.shiftKey) {
}
}
Ok, let's tackle the obvious first, just plain ol' click, which we defined yesterday. The same code we created then will work now, so lets go ahead and insert that. At the same time, we need to start to not only track which items have been selected (with the CSS 'focused' class), but also which item was the last item the user clicked before the current one. This way we have a starting point, and an ending point for the range of elements the user wants to select when they shift click. To do this, we are going to introduce a new CSS class called 'lastSelected'. On every click we need to clear any item with the lastSelected class, and set the currently clicked item as 'lastSelected'. We want to do this after we have done all our processing so we know during shift-select what the last item was. So, at the end of the function, we are going to add two lines almost identical to the focusObject function from the last post, but in addition to using the passed in class name, we are going to add the new .lastSelected class as well.
function focusObject(class,objId,e) {
// Capture the selected node...
var selNode = dojo.byId(objId);
// JUST CLICK
if ((!e.ctrlKey) && (!e.shiftKey)) {
dojo.query(class+'.focused').removeClass('focused');
dojo.addClass(selNode, 'focused');
// CONTROL SHIFT CLICK
} else if ((e.ctrlKey) && (e.shiftKey)) {
// CONTROL CLICK
} else if (e.ctrlKey) {
// SHIFT CLICK
} else if (e.shiftKey) {
}
// Update the last click item to the item the user clicked this time
dojo.query(class + '.lastSelected').removeClass('lastSelected');
dojo.addClass(selNode, 'lastSelected')
}
Notice also how I have removed the calls to dojo.byId() and replaced them with selNode, since we have previously acquired it.
Now lets tackle the next easiest click, the control click. On a control-click the user is simply adding, or removing a previously selected item to the list. There is no need to clear the focused items. So we just need to check to see if selNode already has the focused CSS class, and if so remove it, otherwise, we need to add it. Let's plug in that code now.
function focusObject(class,objId,e) {
// Capture the selected node...
var selNode = dojo.byId(objId);
// JUST CLICK
if ((!e.ctrlKey) && (!e.shiftKey)) {
dojo.query(class+'.focused').removeClass('focused');
dojo.addClass(selNode, 'focused');
// CONTROL SHIFT CLICK
} else if ((e.ctrlKey) && (e.shiftKey)) {
// CONTROL CLICK
} else if (e.ctrlKey) {
if (dojo.hasClass(selNode, 'focused'))
dojo.removeClass(selNode, 'focused')
else
dojo.addClass(selNode, 'focused');
// SHIFT CLICK
} else if (e.shiftKey) {
}
// Update the last click item to the item the user clicked this time
dojo.query(class + '.lastSelected').removeClass('lastSelected');
dojo.addClass(selNode, 'lastSelected')
}
Ok, now we start to get to the tricky parts. The Shifty clicks. Two expected behaviors are expected here. First, if I Shift-Click, I would expect the only items selected to be the items between the last item I selected and the one I select this time, inclusive, or if Control-Shift-Click, I would expect my selections to be logically AND'ed with my previous selections, using again the last item I clicked, and the item clicked this time. Let's start with the Control-Shift-Click.
To accomplish the selection of items within a list of elements, we'll need to introduce a couple of new functions. Here's a run down of them real quick.
dojo.indexOf() - Basically this takes an array in the first argument, and a single item in the second argument, and returns the index of the array in argument 1 where argument 2 appears. If no match is found, it returns a -1.
HTMLNode.parentNode, HTMLNode.childNodes, HTMLNode.previousSibling, and HTML.nextSibling are all functions related to the relative traversal of HTML elements located in the DOM. parentNode returns an element's parent, childNodes returns an array of an element's immediate children, previousSibling and nextSibling return the previous/next immediate html node that is a sibling to itself. This includes whitespace nodes, text, etc, so we have to do a bit of type checking when using these functions.
I chose to start the shifty clicks with the Control Shift Click because we don't have to worry about what has been selected before. We just need to find, and select then inclusive items between our two elements. To do this, we first find the index of our two bounding nodes within our parent node. We do this with a combination of the parentNode, childNodes and dojo.indexOf functions. Here is the code:
var idx = dojo.indexOf(selNode.parentNode.childNodes, selNode);
var lastIdx = dojo.indexOf(selNode.parentNode.childNodes, dojo.query(class+'.lastSelected')[0]);
idx locates the index of the currently selected node in it's parent, and lastIdx locates the index of the last selected item within the currently selected node's parent. We check for the last selected node in the current selected node's parent because this will allow us to have multiple lists on a single page, and would prevent us from selecting from one item in one list to another item in another list. If the last selection is not in the same parent as the current, lastIdx will be -1 and we know we need to reset the selected items, and start a new selection.
Assuming we are in the same list, we compare idx and lastIdx to determine which direction we need to traverse from the currently selected node. If idx > lastIdx, we use nextSibling, and if idx < lastIdx, we use previousSibling. In either case we just traverse from selNode to the last selected nodes, turning on focus for each node along the path that has the passed in class. This is where we need to check the nodeType of each sibling node we retrieve to make sure it is an element that we want to select. You can read about nodeTypes here, but suffice it to say, we are looking for the Element node type, which is type 1. Here is the code to determine if the last two selected nodes are in the same parent, and if so determine the direction to traverse, and then actually performs the selection.
if (lastIdx == -1) { // the last selected was not in the same parent, so we can't shift click, so just reset the focused nodes and select the single node ...
dojo.query(class + '.focused').removeClass('focused');
dojo.addClass(selNode, 'focused');
} else {
if (idx < lastIdx) {
var el = selNode;
for ( ; lastIdx >= idx; idx++) {
if ((el.nodeType == 1) && (dojo.hasClass(el, class.split('.').join(''))))
dojo.addClass(el, 'focused');
el = el.nextSibling;
}
} else if (idx > lastIdx) {
var el = selNode;
for ( ; lastIdx <= idx; idx--) {
if ((el.nodeType == 1) && (dojo.hasClass(el, class.split('.').join(''))))
dojo.addClass(el, 'focused');
el = el.previousSibling;
}
}
}
Now we can worry about the straight shift click. It operates just like control shift click except we need to clear any previously selected items first. Since that is the case, we can simplify our code by removing the seperate check for the control shift click, and integrate the check for a non-control shift click into the same code as above. So, lets start by tweaking our original expanded function template a bit, and add in some code during our shift click code to check for the control key. We'll make a check during the control shift click code we did above, and if they aren't holding down control, we'll clear out all the current selections, re-select the last selected element, and perform the same selection operations as control-shift-click, and wallah, we have shift-click covered too.
function focusObject(class,objId,e) {
// Capture the selected node...
var selNode = dojo.byId(objId);
// JUST CLICK
if ((!e.ctrlKey) && (!e.shiftKey)) {
// JUST CONTROL CLICK
} else if ((e.ctrlKey) && (!e.shiftKey)) {
// SHIFTY CLICKS
} else if (e.shiftKey) {
if (!e.ctrlKey) {
// clear all previous selections first, re-add lastSelected, then process on
dojo.query(class + '.focused').removeClass('focused');
dojo.query(class + '.lastSelected').addClass('focused');
dojo.addClass(selection, 'focused');
}
}
}
Now we can put it all together, and make one last simple adjustment. If the user shift clicks the same element twice, we need to just dump out of our routine since we shouldn't deselect anything, and the last item is already selected. We'll do that right after we get idx and lastIdx, and if they equal each other, we'll just drop out.
So here it is, our final assembled function
function focusObject(class,objId,e) {
var selNode = dojo.byId(objId);
if ((!e.ctrlKey) && (!e.shiftKey)) {
dojo.query(class + '.focused').removeClass('focused');
dojo.addClass(selNode, 'focused');
} else if ((e.ctrlKey) && (!e.shiftKey))
if (dojo.hasClass(selNode, 'focused'))
dojo.removeClass(selNode, 'focused')
else
dojo.addClass(selNode, 'focused');
else if (e.shiftKey) {
var idx = dojo.indexOf(selNode.parentNode.childNodes, selNode);
var lastIdx = dojo.indexOf(selNode.parentNode.childNodes, dojo.query(class + '.lastSelected')[0])
if (idx == lastIdx) {
return true; // user just shift clicked the same node again, don't do anything
}
if (!e.ctrlKey) {
// clear all previous selections first, re-add lastSelected, then process on
dojo.query(class + '.focused').removeClass('focused');
dojo.query(class + '.lastSelected').addClass('focused');
dojo.addClass(selection, 'focused');
}
if (lastIdx == -1) { // the last selected was not in the same parent, so we can't shift click, so just reset the focused nodes and select the single node ...
dojo.query(class + '.focused').removeClass('focused');
dojo.addClass(selNode, 'focused');
} else {
if (idx < lastIdx) {
var el = selNode;
for ( ; lastIdx >= idx; idx++) {
if ((el.nodeType == 1) && (dojo.hasClass(el, class.split('.').join(''))))
dojo.addClass(el, 'focused');
el = el.nextSibling;
}
} else if (idx > lastIdx) {
var el = selNode;
for ( ; lastIdx <= idx; idx--) {
if ((el.nodeType == 1) && (dojo.hasClass(el, class.split('.').join(''))))
dojo.addClass(el, 'focused');
el = el.previousSibling;
}
}
}
}
dojo.query(class + '.lastSelected').removeClass('lastSelected');
dojo.addClass(selNode, 'lastSelected')
}
Now, we are almost there, there are a few more things we need to take care of. First, as in the last post, we need to call focusObject() when our item gets clicked, but now, we have to get the event object and pass it in as well. So our event handler code from the last post for the element changes from this:
focusObject('.userSelectable', '#{id:REPLACEWITHOBJECTID}');
]]>
to this:
focusObject('.userSelectable', '#{id:REPLACEWITHOBJECTID}', ((navigator.appName=="Netscape") ? arguments[0] : event));
]]>
And one last thing, the default browser behavior when you shift click within the body of the HTML page is to high-light the text of the page, of which the end result of all our work would rather hacky, like this:

To prevent this, we'll use some javascript to disable the selection of text on the page. This disables selection of text on the entire document, which for my current use case, is fine, but I am fairly certain this can be adapted to specific elements as well, it is just untested at the moment.
To prevent the selection of text, at the beginning of your client-side javascript library, add the following code:
function disableselect(e){ return false; }
function reEnable(){ return true; }
document.onselectstart=new Function ("return false");
if (window.sidebar){
document.onmousedown=disableselect;
document.onclick=reEnable;
}
And you'll get a nice, clean shift-select:

Well, thats the book (quite literally it appears) on single and multple html element selection. In an upcoming post, I'll show you how to implement this as a practical application add-in along with identifying and working with the selected elements.
Happy Coding!