logo

Simple JavaScript drag`n drop

logo

   JavaScript drag`n drop is very simple thing. Last week some juniors ask me how they can drag a div element. Then I thought to write this simple post..

   To Drag a div it needs 3 mouse events onmousedown, onmousemove and onmouseup. These three events can do all the job.

Live example here at

http://www.apueee.com/tma_examples/dragit_tma.htm

Javascript Code Here :

<script type="text/javascript">
    //initiate variables
    var element;
    var DragNow = false;
    var dx=0;
    var dy=0;
    
    function initDrag(e)
    {    
        e = (e)? e : event;
        
        DragNow = true;
        
        dx = Math.abs(parseInt(element.style.left) - e.clientX);
        dy = Math.abs(parseInt(element.style.top) - e.clientY);
        
        //declare mousemove and mouseup event
        document.onmousemove = startDrag;
        document.onmouseup = stopDrag;
    }
 
    function stopDrag()
    {
        DragNow = false;
    }
    
    function startDrag(e)
    {
        e = (e)? e : event;
       
        if(DragNow)
        {
            element.style.top = (e.clientY - dy) + 'px';
            element.style.left = (e.clientX - dx) + 'px';
        }
    }
    
    window.onload = function()
    {
      //set the draggable element 
      element = document.getElementById(elementId); 
      
      //initiate mousedown event
      element.onmousedown = initDrag;
    }
</script>
 
Here the important thing is that the position of the element must 
be 'absolute'.
That's all about the drag`n drop. 
Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • bodytext
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google
  • description
  • Propeller
  • Simpy
  • Socialogs
  • StumbleUpon
  • Technorati
  • Wists

Viewing 4 Comments

Trackbacks

close Reblog this comment
blog comments powered by Disqus
logo
logo
Powered by Wordpress | Designed by Elegant Themes
9 visitors online now
9 guests, 0 members
Max visitors today: 9 at 05:20 pm GMT+8
This month: 9 at 03-11-2010 05:20 pm GMT+8
This year: 46 at 01-15-2010 12:41 am GMT+8
All time: 51 at 10-22-2009 08:26 am GMT+8