views:

2006

answers:

4

I'm handling the dblclick event on a span in my web app. A side-effect is that the double click selects text on the page. How can I prevent this selection from happening?

+12  A: 
function clearSelection() {
    if(document.selection && document.selection.empty) {
        document.selection.empty();
    } else if(window.getSelection) {
        var sel = window.getSelection();
        sel.removeAllRanges();
    }
}

You can also apply these styles to the span for all non-IE browsers:

span.no_selection {
    -moz-user-select: none; // mozilla browsers
    -khtml-user-select: none; // webkit browsers
}
Paolo Bergantino
Is there any way to actually prevent selection as opposed to removing the selection after the fact? Also, your second if statement could be inside the else if for better readability.
David
You're missing an opening brace in the second if statement </perfectionism>
David
The CSS looks great! Any idea if there's something similar available for IE?
David
Sorry about the mess with the braces; I grabbed that code from another site without checking. Fixed. There's no IE equivalent, I'm afraid.
Paolo Bergantino
Thanks for your help!
David
Best to use -webkit- prefix (this is the preferred prefix for Webkit based browsers) in addition to -moz- (and -khtml- if you have a large Konqueror audience).
eyelidlessness
A: 

or, on mozilla:

document.body.onselectstart = function() { return false; } // Or any html object

On IE,

document.body.onmousedown = function() { return false; } // valid for any html object as well
José Leal
This sollution doesn't allow selecting text at all.
jmav
+2  A: 

A simple Javascript function that makes the content inside a page-element unselectable:

function makeUnselectable(elem) {
  if (typeof(elem) == 'string')
    elem = document.getElementById(elem);
  if (elem) {
    elem.onselectstart = function() { return false; };
    elem.style.MozUserSelect = "none";
    elem.style.KhtmlUserSelect = "none";
    elem.unselectable = "on";
  }
}