Thomas Fuchs
Hi, I'm Thomas Fuchs. I'm the author of Zepto.js, of script.aculo.us, and I'm a Ruby on Rails core alumnus. With Amy Hoy I'm building cheerful software, like Freckle Time Tracking and Every Time Zone and write books like Retinafy.me.
   Want me to speak at your conference? Contact me!

Disabling text-selection for Web 2.0 apps

July 19th, 2005

With rich internet applications, that look and feel like desktop apps, you’ll sooner or later run into the problem of browser text-selection, especially if you use some more advanced UI interaction.

You often just want it off because it gives your users no advantages in usability but messes with the layout, and can make images grayed-out or text unreadable.

So, here’s a quick remedy to this (requires the most current version of the Prototype JavaScript library), which will also allow your users using text-selection in input boxes and textareas as usual:


if(/MSIE/.test(navigator.userAgent)) {
  document.onselectstart = function(event) {
    if(!/input|textarea/i.test(Event.element(event).tagName))
      return false;
  };
  } else { // assume DOM
  document.onmousedown = function(event) {
    if(!/input|textarea/i.test(Event.element(event).tagName))
      return false;
  };
}

You can also extend this to allow more elements having text selection. So, if you want paragraphs have text selection, too, just change the regular expression to:


!/p|input|textarea/i

Or you could implement your own testing function that can do checks on more stuff, like CSS class names or specific ancestor elements.

NB: This kind of thing shouldn’t ever be used on normal websites where the user expects that text and image selection is working. It’s strictly for specialized web apps, where text-selection can interfere with enhanced/customized UI elements. No user wants to copy the text from the submit button, or the ‘drag’ text from a dragging handle. But they will want to be able to copy other text contents from the app, besides expecting text input boxes and textareas to work as they should.