How do I disable text selection with CSS or JavaScript? [duplicate]
Asked Answered
B

5

310

I am making a HTML/CSS/jQuery gallery, with several pages.

I indeed have a "next" button, which is a simple link with a jQuery click listener.

The problem is that if the user click the button several times, the text of the button is selected, and then the full line of text. In my really darky design, that is really ugly and nonsensical.

So here is my question: Can you disable text selection on HTML? If not, I'll terribly miss flash and its high level of configuration on textfields...

Briefs answered 23/9, 2010 at 14:39 Comment(1)
It's 2018 :P Check n try these methods ---> freakyjolly.com/how-to-disable-text-selection-highlightingDecadent
S
352
<div 
 style="-moz-user-select: none; -webkit-user-select: none; -ms-user-select:none; user-select:none;-o-user-select:none;" 
 unselectable="on"
 onselectstart="return false;" 
 onmousedown="return false;">
    Blabla
</div>
Sailfish answered 23/9, 2010 at 14:44 Comment(7)
Still don't work in safari and chrome. I keep that solution, but i also implement one work around for the rest: at each click, replace the html of the link by the html of the link. the text is then updated, and the selection go off after 1 half second!Briefs
The CSS for webkit is similar to the one for Firefox, I edited the answer to add it.Sailfish
@Briefs Works in Chrome 17 and Safari 5.Spinescent
Works in IE and Opera after updateDeform
Is this still good in 2014?Exsect
yes, it is caniuse.com/#feat=user-select-noneRap
Will this affect SEO?Spalato
E
350

UPDATE January, 2017:

According to Can I use, the user-select is currently supported in all browsers except Internet Explorer 9 and earlier versions (but sadly still needs a vendor prefix).


All of the correct CSS variations are:

.noselect {
  -webkit-touch-callout: none; /* iOS Safari */
    -webkit-user-select: none; /* Safari */
     -khtml-user-select: none; /* Konqueror HTML */
       -moz-user-select: none; /* Firefox */
        -ms-user-select: none; /* Internet Explorer/Edge */
            user-select: none; /* Non-prefixed version, currently
                                  supported by Chrome and Opera */
}
<p>
  Selectable text.
</p>
<p class="noselect">
  Unselectable text.
</p>

Note that it's a non-standard feature (i.e. not a part of any specification). It is not guaranteed to work everywhere, and there might be differences in implementation among browsers and in the future browsers can drop support for it.


More information can be found in Mozilla Developer Network documentation.

Extravehicular answered 16/2, 2012 at 15:53 Comment(5)
"correct CSS variations"...? The only correct CSS "variation" is user-select.Nocuous
okay so the others are vendor specific prefixes, I'd presume anyone else would class those are correct variations.Extravehicular
Ha ha, Are you planning on earning all your rep with same answer? NICE :)Singleminded
Everyone should know where this works and where does not caniuse.com/user-select-noneDeform
provided solution is not working for opera browser . How to set the user-select option for operaIlluviation
M
37

Try this CSS code for cross-browser compatibility.

-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-o-user-select: none;
user-select: none;
Mercantilism answered 21/12, 2011 at 23:33 Comment(3)
easy to be a web dev in 2021: user-select: none; is enough.Burget
:( didn't work for meChlamydeous
@naXastandswithUkraine not in Safari unfortunately, and this is assuming everyone keeps their browser up-to-date, which they annoyingly don't. Still with using all the above mentioned for now. 👍Antihalation
E
6

You can use JavaScript to do what you want:

if (document.addEventListener !== undefined) {
    // Not IE
    document.addEventListener('click', checkSelection, false);
} else {
    // IE
    document.attachEvent('onclick', checkSelection);
}

function checkSelection() {
    var sel = {};
    if (window.getSelection) {
        // Mozilla
        sel = window.getSelection();
    } else if (document.selection) {
        // IE
        sel = document.selection.createRange();
    }

    // Mozilla
    if (sel.rangeCount) {
        sel.removeAllRanges();
        return;
    }

    // IE
    if (sel.text > '') {
        document.selection.empty();
        return;
    }
}

Soap box: You really shouldn't be screwing with the client's user agent in this manner. If the client wants to select things on the document, then they should be able to select things on the document. It doesn't matter if you don't like the highlight color, because you aren't the one viewing the document.

Evilminded answered 23/9, 2010 at 16:20 Comment(10)
Soap box rebuttal: I have a button which, when clicked, runs some javascript to change the scale of a picture. There is no reason for the user to select the "+" or "-" inside that button, but most web browsers will end up with the text selected after a few button clicks. Similarly, if you're doing drag-and-drop via javascript, you don't want to select the things you drag something over. That said, I appreciate the fact that you still answered the question even though you disagree with the goal.Bosun
I'll concede that there are circumstances where it can be a valid design choice. But the question mentioned he'd miss Flash with the implication that he'd miss being able to control the user's client. I disagree with that mode of thinking. As a user, I do not like site's redefining how my local software works. It's also an accessibility issue.Evilminded
@jsumners There are plenty of circumstances. Do some out-of-the-box thinking and you'll come up with multiple scenarios. Just because browsers enable this by default does not mean we as programmers should conform. Besides, mobile computing is doing away with traditional means of text selection. So it's becoming increasingly relevant. You make it sound like it's some kind of obsolete hack or something, it's a supported feature (see answers above.)Jacinto
@b1naryatr0phy again, the OP specifically described a scenario in which he wanted to control the user's client purely for aesthetic reasons. His goal had nothing to do with function, be it touch or otherwise. In particular, he states that he would miss the ability to completely control the user's interaction like he could with Flash. I believe that is a broken way of developing for the web and said as much after providing a solution that doesn't rely on potentially unimplemented CSS features (at the time).Evilminded
@jsumners Is it not the website designer's decision how a user interacts with his/her page, regardless of the aesthetic or functional purpose?Jacinto
No. That is completely up to the client and/or user. This question is essentially the same as "how do I control the user's font size?" The answer is, you can't. Sure, you can specify all sorts of stuff in the stylesheet you deliver with the page, but I can throw thing out and use my own stylesheet to do whatever I want. Same thing with JavaScript. But who wants to do that for a random site? No, the user who finds their client altered by a site is likely to never visit it again. Read alistapart.com/articles/dao it's old but still applies.Evilminded
If it were "completely up to the end user", there we be no functional difference between one website to the next. So I honestly can't see how that makes sense. I also fail to understand how this question could be considered identical to controlling the user's font size. Font size isn't a function. Text selection is. Any true programmer would acknowledge there is a fundamental difference.Jacinto
The implication in the question is that the web designer should have ultimate control over how the document is presented to/viewed by the user. With Flash, that sort of control is possible. With plain HTML/CSS/JavaScript, it isn't. So, yes, they are fundamentally the same question: "how do I impose my will on the user with my HTML/CSS/JavaScript?" And, again, the answer is you can't and you shouldn't. Once the data has left your server, you have zero control over how it is ultimately presented.Evilminded
ummm i think you mean if (typeof document.addEventListener....Remy
This is all a moot point. CSS classes both let you define it as a designer, and the user can re-enable it with a user style sheet if they so desire.Cornew
M
5

I'm not sure if you can turn it off, but you can change the colors of it :)

myDiv::selection,
myDiv::-moz-selection,
myDiv::-webkit-selection {
    background:#000;
    color:#fff;
}

Then just match the colors to your "darky" design and see what happens :)

Marguerite answered 23/9, 2010 at 14:42 Comment(4)
You could compress this into one CSS rule. myDiv.webkit::-webkit-selection, myDiv.moz::-moz-selection, myDiv.normal::selection{ background:#000; color:#fff; }Vannavannatta
@yc: use a multiple selector, I shall edit, thanks :)Marguerite
#galleryPagesNavigation a.normal::selection { background:#000; } #galleryPagesNavigation a.moz::-moz-selection { background:#000; } #galleryPagesNavigation a.webkit::-webkit-selection { background:#000; }Briefs
You have "normal" "moz" and "webkit" in there, remove those, copy the updated code out of this answer :)Marguerite

© 2022 - 2024 — McMap. All rights reserved.