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

or

$( ‘element’ ).enableSelection();

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

(function($){
	$.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);
	};

})(jQuery);

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.

1 Star2 Stars3 Stars4 Stars5 Stars (7 votes, average: 5.00 out of 5)
Loading...
pelister
3D modeler and Web designer. Founder of Techlister. Love to build sites using WordPress and Joomla. Interested in Astronomy, project member of SETI (Search for Extra Terrestrial Intelligence).

Tags: , , , ,

Comments (3)

  • Slavi

    |

    That would be nice if you somehow make it hide the content (or generate a NO SCRIPT content) when javascript is disabled.

    Just a thought.

    Thank you

    Reply

  • Fazri

    |

    how to css automatic protect?

    Reply

    • pelister

      |

      do you want to protect text through css instead of jquery

      Reply

Leave a comment

Techlister© - 2012