Disabling text-selection for Web 2.0 apps
July 19th, 2005With 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.
Tweet