Posts Tagged ‘disable enable selection in jquery’

Disable and enable text selection using jQuery

Written by pelister. Posted in Jquery

Disabling text selection on web pages and protecting the content from content scrapers and prying eyes is always a pain in the …, I am going to say head. Though we can implement a lot of methods to protect the content, there is always a way to copy that from webpages. For example a single line of php code using file_get_contents() will read the entire page and you can fetch and filter the content as you like. But there may be scenarios where you may want to disable the text selection, for example a html table where dragging with the mouse over them make it look shabby and untidy. Here is a simple solution to disable text selection with jQuery.

This code is compatible with Firefox, Chrome, IE 8, Opera and Safari. The actual jQuery code is written as a plugin so you can directly apply to any html element like this

$( ‘element’ ).disableSelection();


$( ‘element’ ).enableSelection();

Here is the actual jQuery plugin to enable or disable text selection.

	$.fn.disableSelection = function() {
		return this
		.attr('unselectable', 'on')
		.css('user-select', 'none')
		.css('-moz-user-select', 'none')
		.css('-khtml-user-select', 'none')
		.css('-webkit-user-select', 'none')
		.on('selectstart', false)
		.on('contextmenu', false)
		.on('keydown', false)
		.on('mousedown', false);

	$.fn.enableSelection = function() {
		return this
		.attr('unselectable', '')
		.css('user-select', '')
		.css('-moz-user-select', '')
		.css('-khtml-user-select', '')
		.css('-webkit-user-select', '')
		.off('selectstart', false)
		.off('contextmenu', false)
		.off('keydown', false)
		.off('mousedown', false);


We are pretty much disabling the CSS selection property for each browser and at the same time disabling the events like text selection, right click which displays the default browser context menu, keydown event that disables Ctrl+a and Ctrl+u etc. Enabling text selection is the exact reverse of the disable function. You can view the demo or download the code for further learning.

Hope you like it.

Techlister© - 2012