How to implement a drag-and-drop div from scratch with JavaScript?

omg picture omg · Jun 24, 2009 · Viewed 62.3k times · Source

It should be a combination of CSS and JavaScript. The steps to do should be:

  1. Make it on top of all other elements (which property to specify?)
  2. Catch the event when it is clicked (which event to listen to?)
  3. Move the div as mouse moves.

But what are the details?

Answer

Sampson picture Sampson · Jun 24, 2009

The jQuery Way:

Check out the jQueryUI addons draggable and droppable.

Literally hundreds of hours have been invested into the jQuery framework to make complicated tasks like this almost trivial. Take advantage of the jQuery team's efforts to make programming rich cross-browser applications easier on us all ;)

Chuck Norris' Way:

If you insist on trying this with raw javascript. You'll want to do a few things. One, programmatically set all draggable items to a relative/absolute positioning. If you click a particular item, cause it's top/left values in CSS to reflect the changes made by the x,y axis of the mouse until the click is released. Additionally, you'll want to update the z-index of each draggable when it's clicked to bring it into view.

Tutorial: How to Drag and Drop with Javascript