65.9K
CodeProject is changing. Read more.
Home

Drag and Move an Item

starIconstarIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIcon

2.83/5 (3 votes)

Jul 30, 2008

CPOL
viewsIcon

25491

downloadIcon

234

You can drag and move an item in the page by mouse

Introduction

  1. In the style of your item (like img, div, etc.), make the position as absolute, for example:
    <div style="position:absolute" id="move_id" onmousedown="mousedown()" onmouseup="mouseup()">
  2. You should have a temp for describing the condition of your item. Set the display as none to hide the temp. The value of this input describes the condition. The value 0 means that the item is not dragged. when your mouse is down over the item (onmousedown). This value will set by 1 to be ready for drag and move.
    <input type="text" style="display:none" id="temp_id" value="0"> 
  3. Make the <body> like this:
    <body onmousemove="mousemove();">
  4. Now we can make the JavaScript functions:
    <script language="javascript" type="text/javascript">
    function mousedown()
    {
        document.getElementById("temp_id").value = "1";
        
    }
    function mouseup()
    {
        document.getElementById("temp_id").value = "0";
        document.getElementById("move_id").style.cursor = "default";
    }
    function mousemove()
    {
        if (document.getElementById("temp_id").value == "1")
        {
            document.getElementById("move_id").style.top = event.clientY - 10;
            document.getElementById("move_id").style.left = event.clientX - 50;
            document.getElementById("move_id").style.cursor = "move";
        }
    }
    </script>