Disabling Text Selection For Drag-and-Drop

A common usability problem encountered in Ajax apps is the unintentional selection of text when trying to do a drag-and-drop operation. This javascript function allows you to disable text-selection for a specific element on the page and should work in all modern browsers:

 <script type="text/javascript">
 function disableSelection(element) {
  element.onselectstart = function() {
  return false;
  };
  element.unselectable = "on";
  element.style.MozUserSelect = "none";
  element.style.cursor = "default";
 }
10  </script>

You can't disable text selection with CSS alone because returning false from the onselectstart event is necessary to disable selection in Internet Explorer. You may want to also change the cursor when mousing over your draggable item with a style of "cursor:default" or "cursor:pointer". Even better yet, you can use "cursor:hand" to indicate that dragging is possible.

Here's how you would call it in your page:

 <script type="text/javascript">
 disableSelection(document.getElementById("text"));
 </script>

Should you actually need to copy and paste, you can always view the source.

TweetBacks
Comments
Innocent bystander's Gravatar A better way would be to use preventDefault() (DOM) or Event.returnValue = false (MSIE) in your event handling code.
# Posted By Innocent bystander | 1/24/08 3:41 PM
Narayan Raman's Gravatar Thanks a lot.
Your solution worked well for me in part of a draggable section resizer.

Regards,
Narayan
# Posted By Narayan Raman | 7/13/09 10:46 AM