Making content unselectable with help of CSS

Sometimes, I need to make unselectable the content of a html page for some time while some operations are performed, for example, drag and drop. Unfortunally, not all the browsers support the styles to make the content unselectable. For these browsers, you might create a layer (DIV) to disable selecting. This layer should be positioned absolutely and should have the viewport size. The other way to implement the unselectable behaviour is to create special event handlers with help of javascript. For example, in Internet Explorer, you can use javascript to set a handler for an event onselectstart to cancel the action.

element.onselectstart = function() { return false; }

CSS styles:

.unselectable {
    -webkit-user-select: none; /* Safari, Chrome */
    -khtml-user-select: none; /* Konqueror */
    -moz-user-select: none; /* Firefox */
    user-select: none; /* CSS3 */
}

Hope in the nearest future, we will use only CSS3 property for this need :)

Example of use:

#("#testdiv").bind("mousedown", function (event) {
    $(document.body).addClass("unselectable");
    ...					
});
#(document.body).bind("mousemove", function (event) {
    /* some code */
});
#("#testdiv").bind("mouseup", function (event) {
    $(document.body).removeClass("unselectable");
    ...					
});

4 Responses to “Making content unselectable with help of CSS”

Leave a Reply