Turning off text selection in Javascript

Posted by Larry Karnowski Fri, 24 Oct 2008 19:39:00 GMT

Say you're doing some drag or drag-and-drop operation in Javascript, and you notice that wherever the user drags, the underlying text or other elements are being highlighted. This can obscure what the user is doing, and it just generally feels "wrong." How do you turn that off?

Here's two quick techniques, one for Firefox and another for Internet Explorer & Safari. (Actually, this is IE7. I haven't tested in IE6.)

Firefox

This one is a CSS fix. Just add the following to your stylesheet and then add the "no-selection" class to whatever you're going to drag over.

.no-selection {  -moz-user-select: none; }

Internet Explorer & Safari We have to use Javascript for this one. Call disable when you start your drag behavior, and then re-enable when the drag is complete. Note that calling this function will disable all text selection until you re-enable, so be careful.

// This works for Safari & IE7, and it is safely ignored in Firefox.  You'll have 
// to add a "-moz-user-select:none;" to whatever you don't want selected in Firefox.
function enableDocumentSelection(enable) {
  if(enable) {
    document.onselectstart = _original_onselectstart;
  }
  else {
    _original_onselectstart = document.onselectstart;
    document.onselectstart = function() { return false; }
  }
}

Tags  | 1 comment

Great Lakes Ruby Bash

Posted by Larry Karnowski Fri, 10 Oct 2008 14:07:00 GMT

I'm flying to Ann Arbor, Michigan later today to give my "Usability on Rails" talk at the Great Lakes Ruby Bash tomorrow. If you're attending, please drop me a note (as I don't know a soul that'll be there). I'll also be hanging out on IRC in #glrb and #midwest.rb. I'm hoping to meet some new friends and convince some geeks of the wonderful ways of "teh us4b1l1t13z"!

Tags , , , , , , ,  | 2 comments