Full stack Web Development

HTML5 Drag and Drop

Drag and Drop are part of HTML5 standard. HTML Drag and Drop will enable applications to use drag and drop features in all kinds of browsers.
In simple, Drag and Drop is a very common feature which enables you to grab an object and drag it to any location specified by the user.

Drag and Drop Events

There are a number of events which are fired during various stages of the drag and drop operation. These events are listed below −

  • drag start: It is invoked when the user starts dragging the object.
  • drag enter: It is invoked when the mouse is first moved over the target element while a drag is going to occur.
  • Drag: This event is invoked every time the mouse is moved while the object is being dragged.
  • Dragover: It is invoked when the mouse is moved over an element when a drag occurs.
  • Drag leaves: It is invoked when the mouse leaves an element while a drag occurs.
  • Drop: The drop event is invoked on the element where drop occurs at the end of the drag operation.
  • Dragged: It is invoked when the user releases the mouse button while dragging an object.

Now let us look into a simple Drag and Drop example.
The example below is a simple drag and drop example:

<html>
<head>
<style>
#div1 {width:200px;height:70px;padding:10px;border:1px solid;}
</style>
<script>
function allowDrop(ev) {
    ev.preventDefault();
}
function drag(ev) {
    ev.dataTransfer.setData("text", ev.target.id);
}
function drop(ev) {
    ev.preventDefault();
    var data = ev.dataTransfer.getData("text");
    ev.target.appendChild(document.getElementById(data));
}
</script>
</head>
<body>
<p>Drag the image into the box</p>
<div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
<br>
<img id="drag_box" src="picture.png" draggable="true" ondragstart="drag(event)" width="200" height="69">
</body>
</html>

Now let’s look into how this code works. Let’s begin with the first function:
function allowDrop(ev) {
ev.preventDefault();
}
The call to the preventDefault() function is to prevent the browser default handling of the data. This function allows the image to be dropped in the required location.
Let us now see “How to make an Element Draggable?
Follow these steps to make an element draggable:
To make an element draggable, we need to set the draggable attribute to true:
<img draggable=”true”>
Let’s look into drag function.
function drag(ev) {
ev.dataTransfer.setData(“text”, ev.target.id);
}
The dataTransfer.setData() is used to set the drag operation’s drag data to the specified data and type. In our case, the data type is “text” and the value is the id of the draggable element (“drag1”). The dragged data is the id of the dragged element (“drag1”).
Let’s look into drop function.
function drop(ev) {
ev.preventDefault();
var data = ev.dataTransfer.getData(“text”);
ev.target.appendChild(document.getElementById(data));
}
When the dragged data is dropped, a drop event occurs. The ondrop attribute calls a function, drop(event)
<div ondrop=”drop(event)”>
Now comes the final step – Where to drop the element?
<div id=”div1″ ondrop=”drop(event)” ondragover=”allowDrop(event)”></div>
The ondragover event is used to specifies where the dragged data can be dropped. By default, Bigdata/elements cannot be dropped in other elements. To allow a drop, we must prevent the default handling of the element. This can be done by calling the event.preventDefault() method for the ondragover event.
Nut’s and bolts of drag and drop is to understand data transfer Object
The DataTransfer object is used to assign and read data that is transferred during drag and drop operations. It got a number of properties and methods such as :

Properties


dropEffect – controls the drag-and-drop feedback that the user is given during a drag-and-drop operation. Value provided can be “none”, “copy”, “link”, or “move”.
effectAllowed – Returns the kinds of operations that are to be allowed or can be set to change the allowed operations. The possible values are “none”, “copy”, “copyLink”, “copyMove”, “link”, “linkMove”, “move”, “all”, and “uninitialized”.
files – Returns a FileList of the files being dragged, if any.
items – Returns a DataTransferItems object associated with the DataTransfer object. The same object must be returned each time.
types – Returns a DOMStringList listing the formats that were set in the dragstart event. In addition, if any files are being dragged, then one of the types will be the string “Files”

 Methods


addElement() – Adds the given element to the list of elements used to render the drag feedback.

clearData() – Removes the data of the specified formats. Removes all data if the argument is omitted.

getData() – Returns the specified data. If there is no such data, returns the empty string.

setData() – Adds the specified data.

setDragImage() – Uses the given element to update the drag feedback, replacing any previously specified feedback.

Now the concept you can get to count the number of drag you make it.Let us understand the codes with description.

HTML
<div class="container">
	<div class="row"> <h3>Counts<span id="count" class="badge">Your drag counts here</span>
</h3>
<div class="dragImg"><img width="80" src="https://avatars1.githubusercontent.com/u/10653244?v=4&s
=400/80x80"><span></span></div><div id="dropHere"></div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"
type="text/javascript"></script>
CSS
#dropHere {
    width:400px;
    height: 400px;
    border: 1px  dotted black;
}
$( document ).ready(function() {
   $(function(){
 //Make every clone image unique.
   var counts = [0];
   $(".dragImg").draggable({
     helper: "clone",
    //Create counter
    start: function() { counts[0]++; }
  });
    $("#dropHere").droppable({
       drop: function(e, ui){
         $(this).append($(ui.helper).clone());
   //Pointing to the dragImg class in dropHere and add new class.
         $("#dropHere .dragImg").addClass("item-"+counts[0]).attr('id', "item-"+counts[0])
.append("item-"+counts[0]);
         //  ui.helper.attr('id', "item-"+counts[0]);
       //  alert("count",counts[0]);
          document.getElementById('count').innerHTML = counts[0];
   //Remove the current class (ui-draggable and dragImg)
         $("#dropHere .item-"+counts[0]).removeClass("dragImg ui-draggable ui-draggable-dragging");
$(".item-"+counts[0]).dblclick(function() {
$(this).remove();
});
//make the div draggable --- Not working???
make_draggable($(".item-1"));
}
});
var zIndex = 0;
function make_draggable(elements)
{
	elements.draggable({
		containment:'parent',
		start:function(e,ui){ ui.helper.css('z-index',++zIndex); },
		stop:function(e,ui){
		}
	});
}
});
});

The above code describe is how you can clone the drag event and it will reflect your drag change in the badge. Run and you can do some changes.
We have created one more example which you can learn by refering to our GitHub link https://github.com/somacadgild/DragandDrop.git
In our drag and drop example, we have examined the drag functionality which will be dragged to a specific location. We have used javascript library jquery concept for dragging and dropping.
Please check and revert back to us we will be helping you out.

Conclusion:

I hope you have understood how to drag and drop the elements. If you have any other query do write us at [email protected]
Keep visiting our site www.acadgild.com for more updates on FrontEnd and other technologies.NodeJS course details

Som

is a full-stack web developer, designer, and educator who has been building user interfaces for over a decade. He’s done work for Fortune 4 companies, national political campaigns, and international technology leaders. His proudest achievement is helping people learn full-Stack web development.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Related Articles

Close
Close