HTML draggable Attribute Tutorial

In this section, we will learn what draggable attribute is and how to use it in HTML.

HTML draggable Attribute Definition and Usage

In HTML documents, elements can be designed in a way to move around from one area of a document to another area.

This is actually done with the help of programming languages like JavaScript.

But the first step to drag an element in an HTML document is to make that element draggable in the first place!

This is done with the help of draggable attribute.

So if we set the draggable attribute for an HTML element, that element becomes draggable and we can then use JavaScript to fully implement the drag and drop operation on that element.

Note: check the drag and drop section in JavaScript to learn more on how to do this operation.

HTML draggable Attribute Syntax

<element draggable = “true | false | auto”>

HTML draggable Attribute Values

There are three values that could be used for the draggable attribute:

  • true: if the value is set to true, that means the target element
    is draggable.

  • false: if the value is set to false, that means the target
    element is not draggable.

  • auto: if the value is set to auto, that means it’s the browser
    that should decide whether the target element should be
    draggable.

Example: using draggable attribute in HTML

<!DOCTYPE html>
<html>
<head>
<title>HTML is fun 🙂 </title>
<style type="text/css">
#div1 {
width: 400px;
height: 100px;
padding: 20px;
border: 1px solid #aaaaaa;
}
</style>
</head>
<body >
<div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
<br>
<p id="drag1" draggable="true" ondragstart="drag(event)">This is a draggable sentence. Drag this sentence into the rectangle.</p>
<script type="text/javascript">
function allowDrop(ev) {
ev.preventDefault();
}
function drag(ev) {
ev.dataTransfer.setData("Text", ev.target.id);
}
function drop(ev) {
var data = ev.dataTransfer.getData("Text");
ev.target.appendChild(document.getElementById(data));
ev.preventDefault();
}
</script>
</body>
</html>