Thomas Fuchs
Hi, I'm Thomas Fuchs. I'm the author of the script.aculo.us user interface JavaScript library, a member of the Prototype core team and a Ruby on Rails core alumnus. You're using my work every day, even if you're not aware of it (sounds creepy, I know!). Need JS foo? Hire me.

Disabling text-selection for Web 2.0 apps

July 19th, 2005 by Thomas Fuchs, Comments Off

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.

Post to Twitter Tweet This Post Post to Digg Digg This Post Post to Facebook Share on Facebook

Comments Off

JavaScript Rocks! Peformance ebook
Do you run a web site or web application? Do your users a favor, and grab our ebook on JavaScript performance. Profit from our knowledge gathered in over 15 years of working with the Web and JavaScript and make your sites ultra-fast and your users ultra-happy.

Comments are closed.