Disable text selection in webpage using javascript

In many cases you may need to disable text selection in web page. Where you have drag n drop enabled, you might not want to see that your text get selected when your draggin an item. You can do this easily using this this function.

// this function disables text select on a perticular dom object
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"
}

Now if you want to disable selection on completely on your page you can select the “document” object and disable selection

disableSelection(document)

If you want to disable selection on a particular area such div do this

var div = document.getElementById('my_div');
disableSelection(div)

No related posts.

Tags: ,

To make money we lose our health, and then to restore our health we lose our money.... We live as if we are never going to die, and we die as if we never lived!

1 Comment Leave yours

  1. Really helpfull and simple..
    Thank you so much…

    Wiyono

Leave a Reply