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";
}
</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.

Comments (Comment Moderation is enabled. Your comment will not appear until approved.)
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

Archives By Subject

Calendar

Sun Mon Tue Wed Thu Fri Sat
        1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31

Latest from MXNA

Recent Entries

No recent entries.

Recent Comments

BulletProject Tracker v2.0 Released
Mike said: great app! thanks heaps. found a few bugs in the initial install... -forgot.cfm - no need to inclu... [More]

BulletProject Tracker v2.0 Released
Nathan said: Hi Joe I went to check out the demo site http://ajaxcf.com/project... and it throws an error. Inval... [More]

BulletProject Tracker v2.0 Released
Lachie said: Wow thanks for creating a version 2. I have extensively used version 1 for my projects. It works gre... [More]

BulletProject Tracker v2.0 Released
Steve W said: Joe, You style sheet is missing because a period was left out of the path. <link rel="styl... [More]

BulletProject Tracker v2.0 Released
Mark Mandel said: Joe, Great work! I can't wait to have a play! Btw, your CSS isn't rendering on your post view pag... [More]

RSS


Search

Sponsored Links

Wimpy MP3 Player
Wimpy MP3 Player
easy streaming media
for your coldfusion site



Subscribe

Enter your email address to subscribe to this blog.

Tags

ajax coldfusion