Here's a quick, reusable way to make text unselectable within one or more HTML elements. Actually, here's TWO ways, both useful in certain situations.
The good news with this method is that it's handled completely within
the CSS, if you count IE's proprietary behavior
property. That means you can just add
class="unselectable" and you're done.
The bad news is that you can't just remove the class when you change your mind. Most browsers are fine, but IE's behavior sticks even when the class is gone. If you want to make something selectable again later, check the next section.
<!-- save this file as unselectable.htc and remember where you put it -->
<public:component lightweight="true">
<public:attach event="ondocumentready" onevent="unselectable()" />
<script type="text/javascript">
function unselectable(){
element.onselectstart = function(){ return false; };
element.setAttribute('unselectable', 'on', 0);
}
</script>
</public:component>
.unselectable {
user-select: none;
-moz-user-select: none;
-khtml-user-select: none;
behavior: url(unselectable.htc); /* change this path as needed */
}
This method is library agnostic, just
replace setStyle with the way your preferred library
modifies CSS properties. If you don't use a library, then you
can copy this setStyle to your own code.
function setStyle(element, property, value) {
property = property.replace(/-(\w)/g, function(match, letter) {
return letter.toUpperCase();
});
element.style[property] = value;
}
function selectable(element, bool) {
// most browsers:
setStyle(el, 'user-select', bool ? '' : 'none');
setStyle(el, '-moz-user-select', bool ? '' : 'none');
setStyle(el, '-khtml-user-select', bool ? '' : 'none');
// IE:
element.onselectstart = bool ? null : function() { return false; };
// IE and Opera:
element.setAttribute('unselectable', bool ? '' : 'on', 0);
}
I'm a Front-End Engineer at Yahoo! working on the Mail and Messenger teams. I blog about web design and development topics including accessibility, usability, performance, and developing HTML / CSS / JavaScript applications on Appcelerator Titanium and Adobe AIR.
If you're a web developer, you might enjoy Jelo, my JavaScript library.
All original work on this site is covered by a Creative Commons Attribution 3.0 license unless otherwise specified.
You may share or use any code or images from this site in any manner, for free, so long as reasonable effort has been made to give credit where due.
The views expressed in the posts and comments on this blog do not necessarily reflect the views of Yahoo!