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
Joe Danziger said: @Doug - thanks, glad you like the app! You can add the following to the <cfapplication> call ... [More]

BulletProject Tracker v2.0 Released
Doug said: Great App! How can I increase the time before the session times out? thanks! [More]

BulletProject Tracker v2.0 Released
Joe Danziger said: @Ron - You can access the demo with username admin and password admin. [More]

BulletProject Tracker v2.0 Released
Ron Stewart said: Joe: from the screenshots and the blog entries, this looks pretty cool. I'd like to play in the demo... [More]

BulletProject Tracker v2.0 Released
Mike G said: very very very nice work Dan, nearly blew my load when I saw you even included an API to access ever... [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