0

I am trying to make a moveable div. I know it is a one liner with jQuery, but I don't want to add the 100k+ for this one feature. What I have below works except that when the div moves the rest of the text on the page acts as though the mouse is down and dragging over it (which of course it is) and so the text becomes highlighted or un-highlighted as the mouse moves. Are there any relatively "easy" pure javascript solutions to this?

BTW: thanks to jnoreiga for this code.

window.onload = addListeners;

function addListeners(){
    document.getElementById('moveme').addEventListener('mousedown', mouseDown, false);
    window.addEventListener('mouseup', mouseUp, false);
}

function mouseUp()
{
    window.removeEventListener('mousemove', divMove, true);
}

function mouseDown(e){
  window.addEventListener('mousemove', divMove, true);
}

function divMove(e){
    var div = document.getElementById('moveme');
  div.style.position = 'absolute';
  div.style.top = e.clientY + 'px';
  div.style.left = e.clientX + 'px';
}

And some test html

    <div id="moveme" style="width:100px; background-color:red">Test<br><br>Some more text</div>

    <div style="position:absolute; top:100px; left:50px;">
    <h1>Curriculum</h1>
    <ul>
      <li><a href="#">Math</a></li>
      <li><a href="#">Geometry</a></li>
      <li><a href="#">Physics</a></li>
    </ul>
    </div>
Community
  • 1
  • 1
mseifert
  • 5,390
  • 9
  • 38
  • 100
  • 1
    The whole point of frameworks and libraries is that these little problems have already been solved. If jQuery is too weighty for you, there are alternatives. See: http://stackoverflow.com/questions/3097600/what-are-the-best-light-weight-solutions-for-drag-and-drop – Diodeus - James MacFarlane Oct 16 '13 at 19:56
  • Thank you for the SO link. The second link on that post contained a solution I could modify. – mseifert Oct 17 '13 at 01:14

1 Answers1

0

I was able to find code here which showed me how to make it work. The issue appears to be in setting OnMouseDown to the div that is to be moved. If OnMouseDown is set to window, then the highlighting can be overcome (the tutorial shows how). I had to modify the code shown to search up the tree to find the parent div being clicked on (e.g. if an element in the div is taking the mousedown instead of the div itself.)

mseifert
  • 5,390
  • 9
  • 38
  • 100