Click here to Skip to main content
Click here to Skip to main content

How to Drag Drop in javascript (Part I)

, 11 Jun 2006
Rate this:
Please Sign up or sign in to vote.
Drag and Drop Events used in DHTML object event model.

Introduction

Consider that there is requirement to drag some object e.g image and drop  it over other object from one place to another.This document explains how to achieve this using javascript.

Approach

For any object to participate in drag drop functionality requires to support events which enable drag drop.If object is not supporting these events directly then we should have container object which supports these events.

Sample Code

 

Container which supports drag drop events is required .we are using DIV.

 

<div id='dMain'

ondragstart='fnGetSource();' ondragenter='cancelevent();' ondragover='cancelevent();'                             ondrop='fnGetDestination();'>

 

<img id='Image1'  ></img> //Source Image to be dragged

 

<img id='Image2'  ></img> //target image on which source image will be dropped

 

</div>

 

If we drag Image1 and drop over image2 then Event ondragstart will get fired on source object . function fnGetSource will be executed.we will get id of source object.

 

 

fnGetSource()

{

var srcElementId = event.srcElement.id ;

alert(srcElementId);

}

 

 

When we release mouse over target object ,ondrop event gets fired on target object.This will execute function fnGetDestination.we will get id of destination object

 

fnGetDestination()

{

var destElementId = event.srcElement.id ;

alert(destElementId);

}

 

We need to handle 2 more events ondragenter and ondragover. These events are automatically fired on target object when we start dragging(ondragenter) and drags over valid drop target(ondragover).

 

function cancelevent ()

{

      window.event.returnValue = false;

}

 

Sample Application

Consider sample application where we need to drag image from one area and drop it to another as shown in following screens 1 and 2.

 

 Sample screenshot

 

Sample screenshot
 

 

sample code for testing.

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="test1.aspx.vb" Inherits="test1" %>

 

<!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 images</title>

 

    <script language="JavaScript1.2">

    var srcElementId; //Id of dragged object

    var destElementId; //Id of valid drop target object  

       

    function fnGetSource()

    {

        srcElementId = event.srcElement.id ;

    }   

    function fnGetDestination()

    {

        destElementId = event.srcElement.id;

        var dest = document.getElementById(destElementId).innerHTML ;

        document.getElementById(destElementId).innerHTML = dest + "<br><img src='images/small_0.jpg'  />"     

        document.getElementById("Top").innerHTML =  "";

    }   

    function cancelevent()

    {

        window.event.returnValue = false;

    }

    </script>

 

    <style>

    .cssNormalText

    {

        font-family: Arial, Helvetica, sans-serif;

          font-size: 12px;

    }

</style>

</head>

<body style="background-color: #E3E3E3;">

    <form id="form1" runat="server">

        <table border="0" width="100%">

            <tr>

                <td align="center">

                    <div class="cssNormalText">

                        Drag image from Top box to Empty space in Bottom box.

                    </div>

                </td>

            </tr>

            <tr>

                <td align="center" valign="middle">

                    <div id="Top" style="border: solid 1px black; height: 260px; width: 500px; overflow: auto;

                        background-color: White;" ondragstart='fnGetSource();' ondragover='cancelevent();'>

                        <br />

                        <img src="images/small_0.jpg" />

                    </div>

                </td>

            </tr>

            <tr>

                <td align="center" valign="middle">

                    <div id="bottom" style="border: solid 1px black; height: 260px; width: 500px; background-color: White;"

                        ondragenter='cancelevent();' ondragover='cancelevent();' ondrop='fnGetDestination();'>

                    </div>

                </td>

            </tr>

        </table>

    </form>

</body>

</html>

 

 

 

Events Reference

1.ondragenter Event

Fires on the target element when the user drags the object to a valid drop target.

Syntax

Inline HTML

<ELEMENT ondragenter = "handler" ... >

All platforms

Event property

object.ondragenter = handler

JScript only

object.ondragenter = GetRef("handler")

Visual Basic Scripting Edition (VBScript) 5.0 or later only

Named script

<SCRIPT FOR = object EVENT = ondragenter>

Internet Explorer only

Event Information

Bubbles

Yes

Cancels

Yes

To invoke

  • Drag the selection over a valid drop target within the browser.
  • Drag the selection to a valid drop target within another browser window.

Default action

Calls the associated event handler.

Event Object Properties

Although event handlers in the DHTML Object Model do not receive parameters directly, a handler can query an event object for data.

Remarks

You can handle the ondragenter event on the source or on the target object. Of the target events, it is the first to fire during a drag operation. Target events use the getData method to stipulate which data and data formats to retrieve. The list of drag-and-drop target events includes:

When scripting custom functionality, use the returnValue property to disable the default action.

 

2.ondragover Event

Fires on the target element continuously while the user drags the object over a valid drop target.

Syntax

Inline HTML

<ELEMENT ondragover = "handler" ... >

All platforms

Event property

object.ondragover = handler

JScript only

object.ondragover = GetRef("handler")

Visual Basic Scripting Edition (VBScript) 5.0 or later only

Named script

<SCRIPT FOR = object EVENT = ondragover>

Internet Explorer only

Event Information

Bubbles

Yes

Cancels

Yes

To invoke

  • Drag the selection over a valid drop target within the browser.
  • Drag the selection to a valid drop target within another browser window.

Default action

Calls the associated event handler.

Event Object Properties

Although event handlers in the DHTML Object Model do not receive parameters directly, a handler can query an event object for data.

Remarks

The ondragover event fires on the target object after the ondragenter event has fired.

When scripting custom functionality, use the returnValue property to disable the default action.

3.ondragstart Event

Fires on the source object when the user starts to drag a text selection or selected object.

Syntax

Inline HTML

<ELEMENT ondragstart = "handler" ... >

All platforms

Event property

object.ondragstart = handler

JScript only

object.ondragstart = GetRef("handler")

Visual Basic Scripting Edition (VBScript) 5.0 or later only

Named script

<SCRIPT FOR = object EVENT = ondragstart>

Internet Explorer only

Event Information

Bubbles

Yes

Cancels

Yes

To invoke

Drag the selected text or object.

Default action

Calls the associated event handler.

Event Object Properties

Although event handlers in the DHTML Object Model do not receive parameters directly, a handler can query an event object for data.

Remarks

The ondragstart event is the first to fire when the user starts to drag the mouse. It is essential to every drag operation, yet is just one of several source events in the data transfer object model. Source events use the setData method of the dataTransfer object to provide information about data being transferred. Source events include ondragstart, ondrag, and ondragend.

When dragging anything other than an img object, some text to be dragged must be selected.

 

4.ondrop Event

Fires on the target object when the mouse button is released during a drag-and-drop operation.

Syntax

Inline HTML

<ELEMENT ondrop = "handler" ... >

All platforms

Event property

object.ondrop = handler

JScript only

object.ondrop = GetRef("handler")

Visual Basic Scripting Edition (VBScript) 5.0 or later only

Named script

<SCRIPT FOR = object EVENT = ondrop>

Internet Explorer only

 Event Information

Bubbles

Yes

Cancels

Yes

To invoke

Drag the selection over a valid drop target and release the mouse.

Default action

Calls the associated event handler.

Event Object Properties

Although event handlers in the DHTML Object Model do not receive parameters directly, a handler can query an event object for data.

Remarks

The ondrop event fires before the ondragleave and ondragend events.

When scripting custom functionality, use the returnValue property to disable the default action.

As of Microsoft Internet Explorer 5, drag-and-drop events can be used to carry out drag-and-drop activities, not only with input type=text elements, but also with block and inline tags. For example, text can be selected, dragged, then dropped on a div target. This causes several target events to fire, including ondragenter, ondragover, and ondrop. Because drag-and-drop actions are not directly supported on block and inline tags, you must use extra scripting to carry out the move or copy to the target using innerText, for example.

You must cancel the default action for ondragenter and ondragover in order for ondrop to fire. In the case of a div, the default action is not to drop. This can be contrasted with the case of an input type=text element, where the default action is to drop. In order to allow a drag-and-drop action on a div, you must cancel the default action by specifying window.event.returnValue=false in both the ondragenter and ondragover event handlers. Only then will ondrop fire.

 

5.ondrag Event

Fires on the source object continuously during a drag operation.

6.ondragleave Event

Fires on the target object when the user moves the mouse out of a valid drop target during a drag operation.

7. Ondragend Event

Fires on the source object when the user releases the mouse at the close of a drag operation.

Sequence of event firing

1)Ondragstart :source(ondrag, Ondragend)

2)Ondrag :source (continuously)

3)Ondragenter:target

4)Ondragover:target(continuously)

5)ondrop : target

6)Ondragleave:target

7)Ondragend :source

Technology used

Sample code is developed using Microsoft dot net technology C# .

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

Share

About the Author

Vishal Nagarkar
Program Manager
India India
vishal

Comments and Discussions

 
GeneralHelp please :-) Pinmemberceola4-Mar-10 8:45 
GeneralAmazing work PinmemberExelioindia22-May-08 0:09 
GeneralSome improvments to article PinmemberMaksim Libenson26-Nov-06 0:10 
GeneralRe: Some improvments to article Pinmemberfightinace6-Dec-06 13:07 
Generalhi.. Pinmemberjaymacher4-Jul-06 19:05 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web01 | 2.8.140821.2 | Last Updated 12 Jun 2006
Article Copyright 2006 by Vishal Nagarkar
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid