Search code examples
javascriptdragmousedown

Detect mouse drag and direction using pure javascript


I am trying to detect the mouse direction when dragging the mouse. When the mouse button is down and the user drags the mouse, I want the text to change to left or right depending on the mouse drag direction.

Here's my code.

var divOverlay = document.getElementById ("div");

var dragged = false
window.addEventListener('mousedown', function () { dragged = false })
document.addEventListener('mousemove', function () { dragged = true })
window.addEventListener('mouseup', function(e) {

    
        if (dragged == true && e.pageX <= 0) {
            direction = "left"
        } else if (dragged == true && e.pageX >= 0) {
            direction = "right"
        }
        
        divOverlay.innerHTML = direction;
        
        oldx = e.pageX;
})
#div {
  width: 100px;
  height: 100px;
  background: red;
}
<div id="div"></div>

I don't think I'm too far off but I can't workout what I am doing wrong so I need some help.


Solution

  • Here you go. It just needed a minor tweak.

    var divOverlay = document.getElementById ("div");
    
    var dragged = false
    var oldX = 0;
    window.addEventListener('mousedown', function (e) { oldX = e.pageX; dragged = false })
    document.addEventListener('mousemove', function () { dragged = true })
    window.addEventListener('mouseup', function(e) {
    
        
            if (dragged == true && e.pageX < oldX) {
                direction = "left"
            } else if (dragged == true && e.pageX > oldX) {
                direction = "right"
            }
            
            divOverlay.innerHTML = direction;
            
            
    })
    #div {
      width: 100px;
      height: 100px;
      background: red;
    }
    <div id="div"></div>