Making text unselectable [duplicate]
Asked Answered
H

2

17

So, while playing with scrollbars and stuff in HTML5, I'm starting to notice an annoying trend. If I have text near my element that's being dragged (say, a scrub bar for a video, scroll bar, anything a user would click and drag), nearby text will get selected, as if I'm not using a control, just dragging over the page.

This is terribly annoying, and I can't seem to find the right string to search for on google to figure out if it's possible to make certain elements "unselectable".

Anyone know how to do this?

Haden answered 6/3, 2011 at 0:12 Comment(0)
T
16

It varies per browser. These CSS properties will target WebKit and Gecko-based browsers, as well as any future browsers that support user-select:

user-select: none;
-webkit-user-select: none;
-moz-user-select: none;
Tetzel answered 6/3, 2011 at 0:28 Comment(6)
Awesome! I'm embarrassed that I've made it this far without knowing that.Haden
Just know that the -moz one only makes the appearance of selection invisible, it doesn't disable it functionally. developer.mozilla.org/en/CSS/-moz-user-selectDoublebank
There's also -o-user-select for Opera and the unselectable expando property for IE. See my answer for full details.Hyaloplasm
@Doublebank If it wasn't before, it is now (as I'd expect...). Just saying.Crowns
I just tried it out in a few browsers I have installed for Windows (Fx 3.6 and 13, Chrome 20b, Opera and IE10). Firefox 3.6 seemed to work the best between highlighting the specific element, highlighting sibling elements and content copied to the clipoard with this method. The latest stable Opera still doesn't support blocking any of this and I couldn't get anything to work in IE10, even setting the unselectable="on" attribute.Doublebank
I was wrong about o-user-select: it's never existed. However, Opera does support IE's unselectable attribute.Hyaloplasm
P
1

In IE you can make text immediately within an element unselectable (i.e. doesn't apply to text in its children) by using the unselectable="on" attribute.

Note that if applying from javascript you MUST use el.setAttribute("unselectable","on"). Just trying el.unselectable="on" will not work. (Tested in IE9).

Portwin answered 22/7, 2012 at 9:18 Comment(2)
You're right when IE9 is in standards mode (in compatibility modes the unselectable property works fine). I've now updated five of my answers involving unselectable (apparently that's the maximum number of edits allowed to your own posts in a day. I've no idea why). Odd that one of your edits was approved and an identical one rejected.Hyaloplasm
Some background as to why this change has happened in IE 9: msdn.microsoft.com/en-us/library/ie/gg622931%28v=vs.85%29.aspxHyaloplasm

© 2022 - 2024 — McMap. All rights reserved.