Global draggable Attribute - HTML CSS HTML Global Attribute

HTML CSS examples for HTML Global Attribute:draggable

Description

The draggable attribute specifies whether an element is draggable or not.

Links and images are draggable by default.

Attribute Values

Value Description
true Specifies that the element is draggable
false Specifies that the element in not draggable
auto Uses the default behavior of the browser

A draggable paragraph:

Demo Code

ResultView the demo in separate window

<!DOCTYPE HTML>
<html>
<head>
<style>
#div1 {<!--   w w  w . j a  v  a2  s .c o m-->
    width: 350px;
    height: 70px;
    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) {
    var data = ev.dataTransfer.getData("Text");
    ev.target.appendChild(document.getElementById(data));
    ev.preventDefault();
}
</script>
</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 paragraph. Drag this element into the rectangle.</p>

</body>
</html>

Demo Code

ResultView the demo in separate window

<!DOCTYPE html>
<html lang="en">
 <head>
  <meta charset="UTF-8">
  <title>Example of HTML5 Drag and Drop</title>
  <script type="text/javascript">
    function dragStart(e){<!-- ww w.ja  v  a 2s .c o  m-->
        // Sets the operation allowed for a drag source
        e.dataTransfer.effectAllowed = "move";

        // Sets the value and type of the dragged data
        e.dataTransfer.setData("Text", e.target.getAttribute("id"));
    }
    function dragOver(e){
        // Prevent the browser default handling of the data
        e.preventDefault();
        e.stopPropagation();
    }
    function drop(e){
        // Cancel this event for everyone else
        e.stopPropagation();
        e.preventDefault();

        // Retrieve the dragged data by type
        var data = e.dataTransfer.getData("Text");

        // Append image to the drop box
        e.target.appendChild(document.getElementById(data));
    }
</script>
  <style type="text/css">
    #dropBox{
        width: 200px;
        height: 200px;
        border: 5px dashed gray;
        background: lightyellow;
        text-align: center;
        margin: 20px 0;
        color: orange;
    }
    #dropBox img{
        margin: 10px;
    }
</style>
 </head>
 <body>
  <p>Drag and drop the image into the drop box:</p>
  <div id="dropBox" ondragover="dragOver(event);" ondrop="drop(event);">
  </div>
  <img src="https://www.java2s.com/style/demo/Opera.png" id="dragA" draggable="true" ondragstart="dragStart(event);" width="80" height="80">
 </body>
</html>

Related Tutorials