JavaScript - Prototype Styled Selection Disabling

 

This concept was originally developed on Ajax Cookbook's Disable Text Selection by Bret Taylor, in 2006. I modified it slightly to use as a method for the Prototype library.

  1. Object.extend(Element.Methods, {
  2. disableSelection: function(el) {
  3. with(el) {
  4. onselectstart = function() { return false; };
  5. unselectable = 'on';
  6. style.MozUserSelect = 'none';
  7. style.cursor = 'default';
  8. }
  9. }
  10. });
  11. Element.addMethods();

You can easily call it like this:

  1. <div id="test">abc123</div>
  2. <script type="text/javascript">$('test').disableSelection();</script>

Be sure you include the Element.addMethods(); part, or it won't work. Also, if you're not familiar with the with() statement (searching for "javascript with" on Google is pretty much worthless), read up about it over at the Mozilla Developer Center.