Ads Top

Drag and drop in javascript

How to use drag and drop html5?

Drag and drop are the html5 features. It's easy you want to grab any element to another place then you can use "draggable" attribute in any element and it should be true and also use "ondragstart" attribute. And where you want to drop this element there need to add "ondrop" attribute, also required "ondragover" attribute. As given below code:

Code demo 
 
<style>
    .maindragBoxSimple { border: 2px solid #eee; max-width: 600px;  margin: 20px auto;}
    .maindragBoxSimple span{ background: #0bf;
    width: 30px;
    height: 30px;
    display: block;
    border-radius: 50%;
    text-align: center;
    color: #fff;
    font-family: arial;
    line-height: 28px;}
    .maindragBoxSimple div{ width: 100px; height: 100px; margin: 5px; border: 1px solid #ccc;}
    </style>

    <script>
       function dragSimple(event){
        event.dataTransfer.setData('dragedItem', event.target.id);
       }
       function allowDragSimple(event){
         event.preventDefault();
        }

       function dropSimple(event){
        var dobj = event.dataTransfer.getData('dragedItem');
        event.target.appendChild(document.getElementById(dobj));
       }
    </script>

<div class="maindragBoxSimple">
        <div id="aArea" ondrop="dropSimple(event)" ondragover="allowDragSimple(event)"></div>
        <span id="a" draggable="true" ondragstart="dragSimple(event)">A</span>
    </div>

Second Example Code below:


<style>
    .maindragBoxMultiple { border: 1px solid #ccc; background: #eee; margin: 20px auto; max-width: 600px; }
    .maindragBoxMultiple span{ background: #0bf;
    width: 30px;
    height: 30px;
    display: block;
    border-radius: 50%;
    text-align: center;
    color: #fff;
    font-family: arial;
    line-height: 28px;}
    .maindragBoxMultiple div{ width: 100px; height: 100px; margin: 5px; border: 1px solid #ccc; background: #fff;}

    </style>
    <script>
        var dragItem = '';
       function drag(event){
        dragItem = event.target.id;
       }
       function allowDrag(event){
        event.preventDefault();
        }

       function drop(event){
       
        var arrr = event.target.getAttribute('sheoDrag');
            if(dragItem == arrr){
                event.target.appendChild(document.getElementById(dragItem));
            }
            else{
                alert('Wrong place');
            }
       }
    </script>

<div class="maindragBoxMultiple">
    <div ondrop="drop(event)" ondragover="allowDrag(event)" sheoDrag="a"></div>
    <div ondrop="drop(event)" ondragover="allowDrag(event)" sheoDrag="b"></div>
    <span id="a" draggable="true" ondragstart="drag(event)">A</span>
    <span id="b" draggable="true" ondragstart="drag(event)">B</span>
</div>




No comments:

Copyright Reserved to Anything Learn. Powered by Blogger.