Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • HTML 5 Drag and Drop

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 184
    Comment on it

    Drag and Drop feature allows a user to catch an element and drag it to any page or drop to some other location of the page. Earlier to use the feature of drag and drop programmer either has to create more complex javascript programming or use some third party framework like jquery, etc.

    Now with HMTL5 we can use the DnD (i.e., Drag and Drop) API which is inbuilt in it and is supported by browsers like chrome, safari, Mozilla etc.

    Now let's see step by step how drag and drop features work.

    1.  we have to give draggable attribute value true if we want to make an element draggable.

    <div draggable="true">

    2. Now after making an element draggable we need to specify what needs to be done when an element is dragged. This is done using an event listener ondragstart.

    <div id="source" draggable="true" ondragstart="startdrag(event)" ></div>

    Here I have called drag function on ondragstart listener.

    function startdrag(obj) {
        obj.dataTransfer.setData("text", obj.target.id);
    }

    obj.dataTranfer object gives lots of techniques, here we have called setData() to set the values of the dragged information. 

    3. Presently after dragging the component we have to indicate where we have to drop the component. This is finished by indicating event dragover listener to the objective.

    <div id="target" ondrop="dropItem(event)" ondragover="Allow(event)"></div>

    By default, non-structure components won't do anything or can not be dropped. For not facing this  we have to keep the default handling of the component. Here we have called allowDrop() function:

    function Allow(obj) {
        obj.preventDefault();
    }

    obj.preventDefault() prevents default action of the event to be triggered.

    4. After this drop, an event occurs when the dragged event is released. The drop() function is called on the ondrop attribute.

    function dropItem(obj) {
        obj.preventDefault();
        var val = obj.dataTransfer.getData("text");
        obj.target.appendChild(document.getElementById(val));
    }
    

    obj.dataTranfer.getData() is called to gets the data by specifying the type of data to be collected. After collecting the data the target div is appended with the dragged data.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: