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
2009-05-19 00:58:57
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
2009-05-19 01:07:53
You're missing an opening brace in the second if statement </perfectionism>
David
2009-05-19 01:09:48
The CSS looks great! Any idea if there's something similar available for IE?
David
2009-05-19 01:12:02
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
2009-05-19 01:13:37
Thanks for your help!
David
2009-05-19 01:33:20
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
2009-10-14 20:37:26
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
2009-05-19 01:06:24
+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";
}
}