Author - StudySection Post Views - 200 views
Html5

Html5 Drag and Drop API

Introduction:

The document object model is a key source of data for the HTML5 drag and drop API in order to determine what is being moved or dropped. The outcome is that it enables us to drag and drop any element on the website. The user can click and drag elements with a mouse to drop them by letting go of the mouse button.

Events on draggable elements:

Dragstart: When we begin to drag, it is triggered. We must inform the API of our intended drag targets and define additional parameters at this point.
Drag: While dragging, this event is constantly triggered. It depends on the browser and how frequently it happens. This is helpful for locating the draggable object precisely.
Dragend occurs when a user stops dragging an object with the mouse button pressed.

Events on drop targets:

Dragenter: triggered while a drag is in progress when the mouse is first moved over the target element.
Dragover: This event is triggered whenever a drag is taking place while the mouse is over an element.
Drop: The drop event is fired on the element where the drop took place.

Drag and drop example: In this example, we will create a draggable list in HTML5

<div>
<ul class="list-group" id="dynamic-list">
<li id=1 class=”list” draggable="true">item 1</li>
<li id=2 class=”list” draggable="true">item 2</li>
<li id=3 class=”list” draggable="true">item 3</li>
<li id=4 class=”list” draggable="true">item 4</li>
</ul>
</div>
<script>
//add an event to each li
const AllList= document.querySelectorAll('.list);
AllList.forEach(list => {
list.addEventListener(ondragstart, drag)
list.addEventListener(ondrop, drop);
list.addEventListener(ondragover, dragover);
});
let dragindex = 0;
let dropindex = 0;
let clone = "";
//Drag Event
function drag(ev) {
ev.dataTransfer.setData("text", ev.target.id); //Set id of drag element
}
//Drop Event
function drop(ev) {
ev.preventDefault();
clone = ev.target.cloneNode(true);
let data = ev.dataTransfer.getData("text"); //get id of dragged element
if (clone.id !== data) {
let nodelist = document.getElementById("dynamic-list").childNodes;
for (let i = 0; i < nodelist.length; i++) {
if (nodelist[i].id == data) {
dragindex = i;
}
}
document.getElementById("dynamic-list").replaceChild(document.getElementById(data), ev.target);
document.getElementById("dynamic-list").insertBefore(clone,
document.getElementById("dynamic-list").childNodes[dragindex]);
}
}
function dragover(ev) {
ev.preventDefault();
}

If you need to prove your skills in the .NET framework, get .NET certified on StudySection. StudySection provides .NET certification exam for beginners as well as experts in the .NET framework. This .NET certification can improve your resume’s success rate.

Leave a Reply

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

fiteesports.com rivierarw.com cratosroyalbet betwoon grandpashabet grandpashabet giriş deneme bonusu veren siteler casino siteleri