Dario Sanchez Martinez
Dario Sanchez Martinez

Reputation: 157

How to track the distance the mouse moved?

Heyo,

I'm trying to create a dragable slider in vanilla JS.

For this I'm trying to transform = 'translateX(' + (mouseMovement) + 'px)'; the amount of pixels the mouse has moved in a carouselSlide.addEventListener('dragover', dragOver); event.

However, I don't know how to store a value of the the first time the mouse moved, + or - current position. So far I tried.

//Hover listeners
carouselSlide.addEventListener('dragstart', dragStart);
carouselSlide.addEventListener('dragend', dragEnd);
carouselSlide.addEventListener('dragover', dragOver);

function dragStart(){
    var x = event.clientX;
    dragOver(x);
}

function dragEnd(){
    console.log('end');            
}

var lastX = 0;

function dragOver(x){          

    var currentX = event.clientX - x;

    var mouseMove = currentX - lastX;

    
    
    //Slide Direction
    if (currentX > lastX){
        carouselSlide.style.transform = 'translateX(' + (mouseMove) + 'px)';        
    } else if (currentX < lastX) {
        carouselSlide.style.transform = 'translateX(' + (mouseMove) + 'px)';
    }

    lastX = currentX;
    
}

However, this does not really work. I did find my solutions in another post: Calculate the distance the mouse is moved during mouse button is pressed

However, this is jQuery

Upvotes: 3

Views: 1311

Answers (1)

epascarello
epascarello

Reputation: 207557

One way is to bind it so when you start the event store the variable. I would then bind the other events an listen for the change in position. On end, I would remove the events.

function dragStart(evt) {
  const startX = evt.clientX;

  const handleDrag = function(evt) {
    document.querySelector("#out").textContent = evt.clientX - startX;
  }

  const dragEnd = function(evt) {
    this.removeEventListener("drag", handleDrag);
    this.removeEventListener("dragend", dragEnd);
  }

  this.addEventListener("drag", handleDrag);
  this.addEventListener("dragend", dragEnd);

}

var elem = document.querySelector("#test");
elem.addEventListener('dragstart', dragStart);
#test {
  width: 100%;
  height: 300px;
  background-color: #CCC;
}

#test div {
  width: 100px;
  height: 300px;
  background: yellow;
}
<div id="test">
  <div draggable="true">X</div>
</div>

<div id="out"></div>

Upvotes: 4

Related Questions