Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any way to prevent "deselection" of highlighted text?

Highlight some text on this webpage, then click basically anywhere on the document. Your selection will disappear.

Is there a way to prevent this behavior when the user clicks on a specific element, either by CSS or Javascript?

E.g.:

var element = document.getElementById("foo");
foo.onclick = function(e){
   //some magic here that prevents deselection from occuring
}

or

foo.style.preventDeselect = "true";

Edit: Perhaps I could store the selection, then after "mouseclick" restore the selection? Is there a way to store aselection, and then reselect it?

Thanks!

like image 879
sam Avatar asked Jan 28 '09 03:01

sam


2 Answers

"return false" as well as "e.preventDefault()" in onmousedown works in FF and Safari, but not IE. The only solution for IE, as far as I can tell, is to throw an error.

This works in all browsers (but causes an error in IE, since preventDefault is not a method):

//clicking the 'test' element will not deselect text.
var test = document.getElementById("test");
test.onmousedown = function(e){
  e = e || window.event;
  e.preventDefault();
}

I'd still like to do this error-free in IE, if possible

Thanks to Paolo Bergantino for the the "onmousedown" tip.

like image 55
sam Avatar answered Sep 28 '22 08:09

sam


This works for me on Firefox, haven't tried IE though. Try clicking on the foo.style.preventDeselect = "true"; line when you have text selected. Uses the mousedown event.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
                    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<script>
$(document).ready(function() {
    $('#test').mousedown(function() {
        return false;
    });
});
</script>
<body>

Highlight some text on this webpage, then click basically anywhere on the document. Your selection will disappear.<br><Br>

Is there a way to prevent this behavior when the user clicks on a specific element, either by CSS or Javascript?<br><Br>

E.g.:<br><Br>

var element = document.getElementById("foo");<br>
foo.onclick = function(e){<br>
   //some magic here that prevents deselection from occuring<br>
}<br><Br>

or<br><Br>

<span id='test'>foo.style.preventDeselect = "true";</span><br><Br>

Thanks!<br><Br>

</body>
</html>
like image 44
Paolo Bergantino Avatar answered Sep 28 '22 06:09

Paolo Bergantino