title: HTML Javascript Drag and Drop: Onmousedown or ondragstart
body: <p>I have some javascript which allows elements to be dragged from one div to another. I want to write some code which attaches the element to the mouse cursor during the drag, so the user can see it move places.</p>
  
  <p>I have tried two things which dont quite work. Any advice on how i can tweak my code?</p>
  
  <p><strong>Attempt one</strong></p>
  
  <p>Change positioning of dragged element to absolute and set top,left to the mouse coordinates.
  The problem with this is that it only fires on mouseup.. the element has an <em>ondragstart</em> listener. When i drag the element nothing happens; only when it gets dropped, it attaches to the mouse.</p>
  
  <pre><code>function drag(ev)
  {
  
  
   ev.dataTransfer.setData("Text",ev.target.id);
   var data=ev.dataTransfer.getData("Text");
  
   body = document.getElementById('body');
   mouse = captureMouse(body);
  
  body.addEventListener('mousemove',function(event)
     {
     document.getElementById(data).style.position="absolute";
     document.getElementById(data).style.top=mouse.y+"px";
     document.getElementById(data).style.left=mouse.x+"px";
     },false);
  
  
  }
  
  
  captureMouse = function(element)
  {
  var mouse = {x:100, y:100}
  
  element.addEventListener('mousemove',function(event)
  {
      var x,y;
      if(event.pageX||event.pageY)
      {
          x=event.pageX;
          y=event.pageY;
      }else{
          x=event.clientX+document.body.scrollLeft+document.documentElement.scrollLeft;
          y=event.clientX+document.body.scrollTop+document.documentElement.scrollTop
      }
  
      x-=element.offsetLeft;
      y-=element.offsetTop;
  
      mouse.x=x;
      mouse.y=y;
  
  },false);
  
  return mouse;
  } 
  </code></pre>
  
  <p><strong>attempt two</strong></p>
  
  <p>This uses the same capture mouse function as above. This time, in addition to the ondragstart listener assigned to the element in the HTML, i also put an <strong>onmousedown</strong> listener which fires the below. The problem here is that it clashes with the ondragstart. When i give the target element an absolute position, the inline-block element next to it takes its place and is picked up by ondragstart instead.</p>
  
  <p>Any suggestions? perhaps i should get rid of my ondragstart ondragover etc completely and replace with
  onmousedown and onmouseup listeners?</p>
  
  <pre><code>function absolute(x){
  body = document.getElementById('body');
  mouse = captureMouse(body);
  body.addEventListener('mousemove',function(event){
  document.getElementById(x).style.position="absolute";
  document.getElementById(x).style.top=mouse.y+"px";
  document.getElementById(x).style.left=mouse.x+"px";
  },false);
  }
  </code></pre>