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

Comments

  1. jmaglasang@gmail.com said about 1 year later:

    How can I disable text selection on right click in safari for windows?

    thanks in advance

Comments are disabled