Drag and drop using HTML 5.0


Drag and Drop
Hi

One of the cool feature added in HTML 5.0 i.e drag and drop. Previously we were doing this task by using pure Javascript and Jquery. But we can doing using HTML 5.0 and Javascript in very simple way.

Here just write 3 functions in Javascript i.e
a. allowDrop(ev)
b. drag(ev)
c. drop(ev)

For example if we have to make image as dragable then make there draggable=”True” and ondragstart just call drag function. like this


<img id="img1" src="Water lilies.jpg" draggable="true"
ondragstart="drag(event)" width="336" height="100">


For div where we have to keep this image ondrop just call drop(event) function and on ondragover just call allowDrop function

like this


<div class="DivClass1" ondrop="drop(event)"
        ondragover="allowDrop(event)">Drop Here</div>


The complete HTML code is like this


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Drag and drop</title>
    <style type="text/css">
    .DivClass 
    {
        width:350px;
        height:120px;
        padding:10px;
        border:1px solid #aaaaaa;
     }
     
     .DivClass1 
    {
        width:350px;
        height:120px;
        padding:10px;
        border:5px solid #aaaaaa;
     }
    </style>

    <script type="text/javascript">

        function allowDrop(ev) {
            ev.preventDefault();
        }

        function drag(ev) {
            ev.dataTransfer.setData("Text", ev.target.id);
        }

        function drop(ev) {
            ev.preventDefault();
            var data = ev.dataTransfer.getData("Text");
            ev.target.appendChild(document.getElementById(data));
        }
      </script>
</head>
<body>
    <form id="form1" runat="server">
   <div class="DivClass" ondrop="drop(event)"
        ondragover="allowDrop(event)">Drop Here </div>
        <br />
        

<div class="DivClass1" ondrop="drop(event)"
        ondragover="allowDrop(event)">Drop Here</div>


<img id="img1" src="Water lilies.jpg" draggable="true"
ondragstart="drag(event)" width="336" height="100">


    </form>
</body>
</html>


Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.