Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 205
omg Avatar asked Jun 24 '09 18:06

omg


People also ask

How do I make a draggable div in HTML5?

Creating draggable content # To make other types of content draggable you need to use the HTML5 Drag and Drop APIs. To make an object draggable set draggable=true on that element. Just about anything can be drag-enabled: images, files, links, files, or any markup on your page.

Is drag-and-drop possible using HTML5 and how?

HTML Drag and Drop (DnD) is a feature of HTML5. It is a powerful user interface concept which is used to copy, reorder and delete items with the help of mouse. You can hold the mouse button down over an element and drag it to another location. If you want to drop the element there, just release the mouse button.


1 Answers

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

like image 112
Sampson Avatar answered Oct 08 '22 03:10

Sampson