Dragging and Moving an Element

How do you drag and move an HTML element? I am not talking about HTML5 drag and drop, which is rather straightforward to implement. I am talking about repositioning an element within its parent by dragging.

If you are impatient, go ahead and try out my solution at http://jsfiddle.net/qWHPz/3/.

They key is that, once the user starts to drag, we have to grab all mousemove events. Otherwise, if the user drags by the edge of the element and moves too quickly, the mouse pointer may leave the element and we will no longer get the mousemove event notification. HTML doesn’t give us any direct way to do this. To solve the problem, we have to attach a mousemove event handler for the whole document. Note: as a part of optimization we attach the document level event handlers only for the duration of the dragging.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s