WEBDOOD.COM

Tag: disabling

Unified Javascript disableTextSelection | enableTextSelection

by webdood on Dec.08, 2009, under Javascript, Software Development

Unified Text Selection Disable/Enable Routine

If you’re doing any kind of drag and drop operation in Javascript/DHTML, you will need to temporarily disable and re-enable text selection in your document while the drag operation is going on.

I wrote this block of code today and it was such a tedious hassle, I thought it worth blogging so others wouldn’t have to endure my pain :{.

This works in all browsers except PC Opera.

It DOES work in Mac OSX Safari, Firefox, Chrome and on PC Internet Explorer, Safari, Firefox and Chrome.

////////////////////////////////////////////////////////////////////////////
// UTILITIES - Section contains general-purpose utilties
// =========
////////////////////////////////////////////////////////////////////////////
utilities : {
  // savedValueOf will hold "original" values that we override/restore as needed
  savedValueOf : new Object(),
  disableTextSelection : function() {
    switch (true) {
      case ( typeof document.onselectstart!="undefined" ) : // IE
        this.savedValueOf["onselectstart"] = document.onselectstart;
        document.onselectstart=function() { return false; };
        break;
      case ( typeof document.body.style.MozUserSelect != "undefined" ) : // Firefox
        this.savedValueOf["-moz-user-select"] = document.body.style.MozUserSelect || "text";
document.body.style.MozUserSelect="none";
        break;
      case ( document.body.style["-khtml-user-select"] != "undefined" ) : // Safari
        this.savedValueOf["-khtml-user-select"] = document.body.style["-khtml-user-select"];
        document.body.style["-khtml-user-select"] = 'none';
        break;
    }
  },
  // enableTextSelection -simply restores *whatever* the previous selection mode was
  // ===============  for the particular browser
  enableTextSelection : function() {
    switch (true) {
      case ( typeof document.onselectstart!="undefined" ) : // IE
        document.onselectstart = this.savedValueOf["onselectstart"]
        break;
      case (typeof document.body.style.MozUserSelect != "undefined") :  // Firefox
        document.body.style.MozUserSelect = this.savedValueOf["-moz-user-select"]
        break;
      case ( document.body.style["-khtml-user-select"]!="undefined" ) : // Safari
        document.body.style["-khtml-user-select"] = this.savedValueOf["-khtml-user-select"];
        break;
    }
  }
}

Shannon Norrell

This posting now also on GitHub

Leave a Comment :, , , more...

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Blogroll

A few highly recommended websites...

  • A List Apart
  • Dive into HTML5
  • Javascript: The Good Parts
  • QuirksMode.org