2

There is a method to do it with CSS, but it is a non-standard feature:

::selection {
    background: transparent;
}

::-moz-selection {
    background: transparent;
}

Is there a way to do it in JavaScript? More on ::selection can be found at caniuse.

Brad
  • 159,648
  • 54
  • 349
  • 530
  • 4
    I certainly hope not! – Evan Davis Jul 22 '14 at 19:33
  • You're trying to use JavaScript as a polyfill for this CSS feature? Or you need to know how to update CSS for elements with JavaScript? – Brad Jul 22 '14 at 19:34
  • I guess my question isn't clear sorry about that. I want to know how to use JavaScript to achieve the same effect i.e. stop the user from highlighting the text. –  Jul 22 '14 at 19:35
  • @Brad I think he wants a javascript method because his CSS method isn't support on all browsers. Mostly mobile ones. – Danny Jul 22 '14 at 19:36
  • @Danny Yes that is exactly what I want to find out. –  Jul 22 '14 at 19:37
  • I know the post I marked duplicate of is titled "CSS" but there are JavaScript solutions discussed in the answers there. – rink.attendant.6 Jul 22 '14 at 19:38
  • 2
    @rink.attendant.6 That is not a duplicate at all. Marking something as a duplicate requires that the questions are the same, not that they have the same answers. – Brad Jul 22 '14 at 19:38
  • Your css solution still allows the selection of text it just makes the background of the selected text transparent. Is that what you want or do you want the selection of text to be disabled completely? – Danny Jul 22 '14 at 19:46

3 Answers3

0

Yes, you can listen for the onselectstart event and cancel it. Here's an example.

tmcw
  • 11,536
  • 3
  • 36
  • 45
  • Out of curiosity, you can see that if you highlight the "This is text you can" in your example, starting from the end. You can scroll up and highlight the un-highlightable text. Is there a way to prevent that or would you just have to apply the onselectstart to the whole page? – DasBeasto Jul 22 '14 at 20:16
  • You would use onselectstart with the whole page. – tmcw Jul 22 '14 at 20:56
0

I know you want a js solution, but this css style should work for all main browsers:

.nohighlight{
    -webkit-touch-callout: none;
    -webkit-user-select: none;
    -khtml-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
}
Mauriel
  • 36
  • 4
0

Try this out

function disableSelection(target){
    if (typeof target.onselectstart!="undefined") // IE
        target.onselectstart=function(){return false;};
    else if (typeof target.style.MozUserSelect!="undefined") // Firefox
        target.style.MozUserSelect="none";
    else // Opera and the others
        target.onmousedown=function(){return false;};
    target.style.cursor = "default";
}

Usage :

disableSelection(document.body);

Working jsBin

hex494D49
  • 9,109
  • 3
  • 38
  • 47