[javascript] Is there a way to make text unselectable on an HTML page?

I'm building an HTML UI with some text elements, such as tab names, which look bad when selected. Unfortunately, it's very easy for a user to double-click a tab name, which selects it by default in many browsers.

I might be able to solve this with a JavaScript trick (I'd like to see those answers, too) -- but I'm really hoping there's something in CSS/HTML directly that works across all browsers.

This question is related to javascript html css cross-browser textselection

The answer is


Images can be selected too.

There are limits to using JavaScript to deselect text, as it might happen even in places where you want to select. To ensure a rich and successful career, steer clear of all requirements that need ability to influence or manage the browser beyond the ordinary... unless, of course, they are paying you extremely well.


I'm finding some level of success with the CSS described here http://www.quirksmode.org/css/selection.html:

::selection {
    background-color: transparent;
}

It took care of most of the issues I was having with some ThemeRoller ul elements in an AIR application (WebKit engine). Still getting a small (approx. 15 x 15) patch of nothingness that gets selected, but half the page was being selected before.


Try this:

<div onselectstart="return false">some stuff</div>

Simple, but effective... works in current versions of all major browsers.


There are many occasions when turning off selectability enhances the user experience.

For instance allowing the user to copy a block of text on the page without copying the text of any interface elements associated with it (that would become interspersed within the text being copied).


Here's a Sass mixin (scss) for those interested. Compass/CSS 3 doesn't seem to have a user-select mixin.

// @usage use within a rule
// ex. img {@include user-select(none);}
// @param assumed valid user-select value
@mixin user-select($value)
{
    & {
        -webkit-touch-callout: $value;
        -webkit-user-select: $value;
        -khtml-user-select: $value;
        -moz-user-select: $value;
        -ms-user-select: $value;
        user-select: $value;
    }
}

Though Compass would do it in a more robust way, i.e. only add support for vendors you've chosen.


The following works in Firefox interestingly enough if I remove the write line it doesn't work. Anyone have any insight why the write line is needed.

<script type="text/javascript">
document.write(".");
document.body.style.MozUserSelect='none';
</script>

Absolutely position divs over the text area with a z-index higher and give these divs a transparent GIF background graphic.

Note after a bit more thought - You'd need to have these 'covers' be linked so clicking on them would take you to where the tab was supposed to, which means you could/should do this with the anchor element set to display:box, width and height set as well as the transparent background image.


All of the correct CSS variations are:

-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;

Any JavaScript or CSS method is easily circumvented with Firebug (like Flickr's case).

You can use the ::selection pseudo-element in CSS to alter the highlight color.

If the tabs are links and the dotted rectangle in active state is of concern, you can remove that too (consider usability of course).


Images can be selected too.

There are limits to using JavaScript to deselect text, as it might happen even in places where you want to select. To ensure a rich and successful career, steer clear of all requirements that need ability to influence or manage the browser beyond the ordinary... unless, of course, they are paying you extremely well.


Absolutely position divs over the text area with a z-index higher and give these divs a transparent GIF background graphic.

Note after a bit more thought - You'd need to have these 'covers' be linked so clicking on them would take you to where the tab was supposed to, which means you could/should do this with the anchor element set to display:box, width and height set as well as the transparent background image.


For Firefox you can apply the CSS declaration "-moz-user-select" to "none". Check out their documentation, user-select.

It's a "preview" of the future "user-select" as they say, so maybe Opera or WebKit-based browsers will support that. I also recall finding something for Internet Explorer, but I don't remember what :).

Anyway, unless it's a specific situation where text-selecting makes some dynamic functionality fail, you shouldn't really override what users are expecting from a webpage, and that is being able to select any text they want.


Here's a Sass mixin (scss) for those interested. Compass/CSS 3 doesn't seem to have a user-select mixin.

// @usage use within a rule
// ex. img {@include user-select(none);}
// @param assumed valid user-select value
@mixin user-select($value)
{
    & {
        -webkit-touch-callout: $value;
        -webkit-user-select: $value;
        -khtml-user-select: $value;
        -moz-user-select: $value;
        -ms-user-select: $value;
        user-select: $value;
    }
}

Though Compass would do it in a more robust way, i.e. only add support for vendors you've chosen.


Try this:

<div onselectstart="return false">some stuff</div>

Simple, but effective... works in current versions of all major browsers.


For Safari, -khtml-user-select: none, just like Mozilla's -moz-user-select (or, in JavaScript, target.style.KhtmlUserSelect="none";).


For an example of why it might be desirable to suppress selection, see SIMILE TImeline, which uses drag-and-drop to explore the timeline, during which accidental vertical mouse movement causes the labels to be highlighted unexpectedly, which looks weird.


<script type="text/javascript">

/***********************************************
* Disable Text Selection script- © Dynamic Drive DHTML code library (www.dynamicdrive.com)
* This notice MUST stay intact for legal use
* Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code

***********************************************/


function disableSelection(target){

    if (typeof target.onselectstart!="undefined") //IE route
        target.onselectstart=function(){return false}

    else if (typeof target.style.MozUserSelect!="undefined") //Firefox route
        target.style.MozUserSelect="none"

    else //All other route (ie: Opera)
        target.onmousedown=function(){return false}

    target.style.cursor = "default"
}



//Sample usages
//disableSelection(document.body) //Disable text selection on entire body
//disableSelection(document.getElementById("mydiv")) //Disable text selection on element with id="mydiv"


</script>

EDIT

Code apparently comes from http://www.dynamicdrive.com


If it looks bad you can use CSS to change the appearance of selected sections.


There are many occasions when turning off selectability enhances the user experience.

For instance allowing the user to copy a block of text on the page without copying the text of any interface elements associated with it (that would become interspersed within the text being copied).


If it looks bad you can use CSS to change the appearance of selected sections.


<script type="text/javascript">

/***********************************************
* Disable Text Selection script- © Dynamic Drive DHTML code library (www.dynamicdrive.com)
* This notice MUST stay intact for legal use
* Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code

***********************************************/


function disableSelection(target){

    if (typeof target.onselectstart!="undefined") //IE route
        target.onselectstart=function(){return false}

    else if (typeof target.style.MozUserSelect!="undefined") //Firefox route
        target.style.MozUserSelect="none"

    else //All other route (ie: Opera)
        target.onmousedown=function(){return false}

    target.style.cursor = "default"
}



//Sample usages
//disableSelection(document.body) //Disable text selection on entire body
//disableSelection(document.getElementById("mydiv")) //Disable text selection on element with id="mydiv"


</script>

EDIT

Code apparently comes from http://www.dynamicdrive.com


Any JavaScript or CSS method is easily circumvented with Firebug (like Flickr's case).

You can use the ::selection pseudo-element in CSS to alter the highlight color.

If the tabs are links and the dotted rectangle in active state is of concern, you can remove that too (consider usability of course).


For an example of why it might be desirable to suppress selection, see SIMILE TImeline, which uses drag-and-drop to explore the timeline, during which accidental vertical mouse movement causes the labels to be highlighted unexpectedly, which looks weird.


All of the correct CSS variations are:

-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;

<script type="text/javascript">

/***********************************************
* Disable Text Selection script- © Dynamic Drive DHTML code library (www.dynamicdrive.com)
* This notice MUST stay intact for legal use
* Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code

***********************************************/


function disableSelection(target){

    if (typeof target.onselectstart!="undefined") //IE route
        target.onselectstart=function(){return false}

    else if (typeof target.style.MozUserSelect!="undefined") //Firefox route
        target.style.MozUserSelect="none"

    else //All other route (ie: Opera)
        target.onmousedown=function(){return false}

    target.style.cursor = "default"
}



//Sample usages
//disableSelection(document.body) //Disable text selection on entire body
//disableSelection(document.getElementById("mydiv")) //Disable text selection on element with id="mydiv"


</script>

EDIT

Code apparently comes from http://www.dynamicdrive.com


Absolutely position divs over the text area with a z-index higher and give these divs a transparent GIF background graphic.

Note after a bit more thought - You'd need to have these 'covers' be linked so clicking on them would take you to where the tab was supposed to, which means you could/should do this with the anchor element set to display:box, width and height set as well as the transparent background image.


Try this:

<div onselectstart="return false">some stuff</div>

Simple, but effective... works in current versions of all major browsers.


For Firefox you can apply the CSS declaration "-moz-user-select" to "none". Check out their documentation, user-select.

It's a "preview" of the future "user-select" as they say, so maybe Opera or WebKit-based browsers will support that. I also recall finding something for Internet Explorer, but I don't remember what :).

Anyway, unless it's a specific situation where text-selecting makes some dynamic functionality fail, you shouldn't really override what users are expecting from a webpage, and that is being able to select any text they want.


Try this:

<div onselectstart="return false">some stuff</div>

Simple, but effective... works in current versions of all major browsers.


For Firefox you can apply the CSS declaration "-moz-user-select" to "none". Check out their documentation, user-select.

It's a "preview" of the future "user-select" as they say, so maybe Opera or WebKit-based browsers will support that. I also recall finding something for Internet Explorer, but I don't remember what :).

Anyway, unless it's a specific situation where text-selecting makes some dynamic functionality fail, you shouldn't really override what users are expecting from a webpage, and that is being able to select any text they want.


Images can be selected too.

There are limits to using JavaScript to deselect text, as it might happen even in places where you want to select. To ensure a rich and successful career, steer clear of all requirements that need ability to influence or manage the browser beyond the ordinary... unless, of course, they are paying you extremely well.


"If your content is really interesting, then there is little you can ultimately do to protect it"

That's true, but most copying, in my experience, has nothing to do with "ultimately" or geeks or determined plagiarists or anything like that. It's usually casual copying by clueless people, and even a simple, easily defeated protection (easily defeated by folks like us, that is) works quite well to stop them. They don't know anything about "view source" or caches or anything else... heck, they don't even know what a web browser is or that they're using one.


Absolutely position divs over the text area with a z-index higher and give these divs a transparent GIF background graphic.

Note after a bit more thought - You'd need to have these 'covers' be linked so clicking on them would take you to where the tab was supposed to, which means you could/should do this with the anchor element set to display:box, width and height set as well as the transparent background image.


The following works in Firefox interestingly enough if I remove the write line it doesn't work. Anyone have any insight why the write line is needed.

<script type="text/javascript">
document.write(".");
document.body.style.MozUserSelect='none';
</script>

For Safari, -khtml-user-select: none, just like Mozilla's -moz-user-select (or, in JavaScript, target.style.KhtmlUserSelect="none";).


If it looks bad you can use CSS to change the appearance of selected sections.


"If your content is really interesting, then there is little you can ultimately do to protect it"

That's true, but most copying, in my experience, has nothing to do with "ultimately" or geeks or determined plagiarists or anything like that. It's usually casual copying by clueless people, and even a simple, easily defeated protection (easily defeated by folks like us, that is) works quite well to stop them. They don't know anything about "view source" or caches or anything else... heck, they don't even know what a web browser is or that they're using one.


For an example of why it might be desirable to suppress selection, see SIMILE TImeline, which uses drag-and-drop to explore the timeline, during which accidental vertical mouse movement causes the labels to be highlighted unexpectedly, which looks weird.


Images can be selected too.

There are limits to using JavaScript to deselect text, as it might happen even in places where you want to select. To ensure a rich and successful career, steer clear of all requirements that need ability to influence or manage the browser beyond the ordinary... unless, of course, they are paying you extremely well.


<script type="text/javascript">

/***********************************************
* Disable Text Selection script- © Dynamic Drive DHTML code library (www.dynamicdrive.com)
* This notice MUST stay intact for legal use
* Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code

***********************************************/


function disableSelection(target){

    if (typeof target.onselectstart!="undefined") //IE route
        target.onselectstart=function(){return false}

    else if (typeof target.style.MozUserSelect!="undefined") //Firefox route
        target.style.MozUserSelect="none"

    else //All other route (ie: Opera)
        target.onmousedown=function(){return false}

    target.style.cursor = "default"
}



//Sample usages
//disableSelection(document.body) //Disable text selection on entire body
//disableSelection(document.getElementById("mydiv")) //Disable text selection on element with id="mydiv"


</script>

EDIT

Code apparently comes from http://www.dynamicdrive.com


I'm finding some level of success with the CSS described here http://www.quirksmode.org/css/selection.html:

::selection {
    background-color: transparent;
}

It took care of most of the issues I was having with some ThemeRoller ul elements in an AIR application (WebKit engine). Still getting a small (approx. 15 x 15) patch of nothingness that gets selected, but half the page was being selected before.


If it looks bad you can use CSS to change the appearance of selected sections.


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to css

need to add a class to an element Using Lato fonts in my css (@font-face) Please help me convert this script to a simple image slider Why there is this "clear" class before footer? How to set width of mat-table column in angular? Center content vertically on Vuetify bootstrap 4 file input doesn't show the file name Bootstrap 4: responsive sidebar menu to top navbar Stylesheet not loaded because of MIME-type Force flex item to span full row width

Examples related to cross-browser

Show datalist labels but submit the actual value Stupid error: Failed to load resource: net::ERR_CACHE_MISS Click to call html How to Detect Browser Back Button event - Cross Browser How can I make window.showmodaldialog work in chrome 37? Cross-browser custom styling for file upload button Flexbox and Internet Explorer 11 (display:flex in <html>?) browser sessionStorage. share between tabs? How to know whether refresh button or browser back button is clicked in Firefox CSS Custom Dropdown Select that works across all browsers IE7+ FF Webkit

Examples related to textselection

Get the Highlighted/Selected text How do I disable text selection with CSS or JavaScript? How to make HTML Text unselectable How to disable text selection highlighting Is there a way to make text unselectable on an HTML page?