views:

187

answers:

3

I'm implementing item selection functionality in javascript (using jQuery). item is a li that contains some html.
the user can click on one item (makes it selected) and then shift-click on another item to select all the items in between. this basically works OK, however the shift-click also selects (higtlights) the text that appears inside the items (the basic browser functionality for shift clicks). is there any way to disable this?

A: 

Try this after the Shift + click...

document.getSelection().removeAllRanges();

If that is not effective enough, you might have to also cancel the onselectstart event...

window.onload = function() {
  document.onselectstart = function() {
    return false;
  }
}
Josh Stodola
+5  A: 

Try a combo of JavaScript and css to prevent the selection in the first place:

$('li').attr('unselectable', 'on'); // IE

css (for browsers not IE):

li {
    user-select: none; /* CSS3 */
    -moz-user-select: none; /* Gecko (Firefox) */
    -khtml-user-select:none; /* Webkit (Safari, Chrome) */
}
Roatin Marth
A: 

I have an application like that. Trick is, I wanted to allow selection, but I also wanted Ctrl-click and Shift-click for selecting items.

What I found was that everyone but IE allows you to beat this by canceling the mousedown event, and in IE what works best is to temporarily disable onselectstart:

$("#id").mousedown(function (e) {
    if (e.ctrlKey || e.shiftKey) {
        // For non-IE browsers
        e.preventDefault();

        // For IE
        if ($.browser.msie) {
            this.onselectstart = function () { return false; };
            var me = this;  // capture in a closure
            window.setTimeout(function () { me.onselectstart = null; }, 0);
        }
    }
});
Anthony Mills