JavaScript HTML5 Drag and Drop (JHDD)


JHDD:   SOLD       




Drag and Drop is part of the HTML5 standard and has become a common feature, the way it works is when you "grab" it and then drag it to a provided location.

Learn HTML5 Drag and Drop
Learn HTML5 Drag and Drop

Below are the specifications of browsers that support the Drag and Drop feature:

Example:

<html>
<!-- bundet.com -->
<head>
</head>
<body>
<h1>Drag and Drop1</h1>
<p>Drag gambar ke dalam persegi panjang</p>
<div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)">
</div>
<br />
<img id="drag1" src="110.jpg" draggable="true" ondragstart="drag(event)" width="336" height="80">
</body>
</html>

<style type="text/css">
 #div1 {
     width :350px;
     height :100px;
     padding :10px;
     border :1px solid #aaaaaa
    }
</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>

The result is as shown in the demo image above. The code above may seem complicated if we look at it as a whole, but let's try to peel each component one by one:

1. Creating Draggable Elements

First of all we set the dragable attribute to "true"

What to drag - ondragstart and setData()

Next, define what should happen when the element is dragged. In the example above, the ondragstart attribute calls a function, drag(event), that specifies what data will be dragged.

The dataTransfer.setData() is a setting method for the data type and values ​​of the dragged data:

In this section, the data type "text" indicates the id value of the draggable element ("drag1").

2. Where is the place for Drop - ondragover?

Even ondragover determines where Drag data can be dropped. By default, data/elements cannot be dropped into other elements. To allow a Drop, we must prevent the default handling of the element.

This is done by calling  event.preventDefault() the method for the ondragover event:

ev.preventDefault();

3. Do Drop - ondrop

When the dragged data is dropped, a drop event occurs. In the above example, the ondrop attribute calls the function, drop(event):

Code Explanation:

  • Call preventDefault() to prevent browser handling by default (opens as link on drop)
  • Get the dragged data with the dataTransfer.getData() method. This method will return any data with the same data type as specified in the setData() method.
  • The dragged data is the id of the dragged data element ("drag1")
  • Adds the dragged element to the Drop element.

Post a Comment

Previous Next

نموذج الاتصال