Thursday, May 5, 2011

Disable Text Selection using Javascript

In the web development cycle, at times we come to a requirement where we need to disable text selection for some HTML Tags i.e. "Do not allow to select text present in some particular Div tag, or span tag or text present in some table" in that case we can use following function. Actually this JavaScript function can be used to Disable Text selection for whole body of the HTML.

function disableSelection(target) {
        if (typeof target.onselectstart != "undefined") //IE route
            target.onselectstart = function () { return false }
        else if (typeof target.style.MozUserSelect != "undefined") //Firefox route
            target.style.MozUserSelect = "none"
        else //All other route (ie: Opera)
            target.onmousedown = function () { return false }
        target.style.cursor = "default"
    }


Define above function in HEAD tag and call this function either on some form event or directly at the bottom of the HTML page.

//disableSelection(document.body) //Disable text selection on entire body

disableSelection(document.getElementById("mydiv")) //Disable text selection on element with id="mydiv"

This is very small function but it was very useful for one of my project.
Submit this story to DotNetKicks

1 comments:

joseph September 7, 2011 at 4:11 PM  

Thanks for sharing such useful information. The information provided is very very niche and this information is not available so easily. Therefore I thank the writer for the useful input.


ASP Development