start blog post

Unselectable Text Using CSS and JavaScript

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.

Adding and Removing a CSS Class

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 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);
    .unselectable {
        user-select: none;
        -moz-user-select: none;
        -khtml-user-select: none;
        behavior: url(; /* change this path as needed */

CSS via JavaScript

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();
        });[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);

var tags = [, , ];

  • share this post:
  • email a friend
  • float this post
  • digg this post
  • share on stumbleupon
  • submit to technorati
  • tweet this post

end blog post

most viewed this week

least viewed this week