Tuesday, December 8, 2009

Unified Javascript disableTextSelection | enableTextSelection

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 : new Object(), // savedValueOf will hold "original" values that we override/restore as needed
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 : 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