how to implement mousemove while mouseDown pressed js
Asked Answered
A

4

17

I have to implement mouse move event only when mouse down is pressed.

I need to execute "OK Moved" only when mouse down and mouse move.

I used this code

 $(".floor").mousedown(function() {
  $(".floor").bind('mouseover',function(){
      alert("OK Moved!");
  });
})
.mouseup(function() {
 $(".floor").unbind('mouseover');
});
Accoucheur answered 13/6, 2015 at 10:19 Comment(0)
F
23

Use the mousemove event.

From mousemove and mouseover jquery docs:

The mousemove event is sent to an element when the mouse pointer moves inside the element.

The mouseover event is sent to an element when the mouse pointer enters the element.

Example: (check console output)

$(".floor").mousedown(function () {
    $(this).mousemove(function () {
        console.log("OK Moved!");
    });
}).mouseup(function () {
    $(this).unbind('mousemove');
}).mouseout(function () {
    $(this).unbind('mousemove');
});

https://jsfiddle.net/n4820hsh/

Fortran answered 13/6, 2015 at 11:27 Comment(2)
when u click in the box for the first time and move the mouse it works well , but when u move the mouse again the without button pressed it also work ! this is what i suffer from : 3 . i need to work only when mouse press and move .Accoucheur
edited: need to unbind also when we leave the box. Now it should work only when you press the mouse inside the box and you move inside.Mortmain
H
12

In pure javascript, you can achieve this with

function mouseMoveWhilstDown(target, whileMove) {
    var endMove = function () {
        window.removeEventListener('mousemove', whileMove);
        window.removeEventListener('mouseup', endMove);
    };

    target.addEventListener('mousedown', function (event) {
        event.stopPropagation(); // remove if you do want it to propagate ..
        window.addEventListener('mousemove', whileMove);
        window.addEventListener('mouseup', endMove);   
    });
}

Then using the function along the lines of

mouseMoveWhilstDown(
    document.getElementById('move'),
    function (event) { console.log(event); }
);

(nb: in the above example, you don't need the function - you could call it as mouseMoveWhilstDown(document.getElementById('move'), console.log), but you might want to do something with it other than output it to the console!)

Hetzel answered 28/3, 2019 at 12:54 Comment(3)
this solution is great , thanks( +1 )Tanny
This is very elegant code, I wasn't even looking for a solution to this problem, but I'm definitely going to use this in the future.Interviewer
This just keep going and going even when no longer mousedown or mousemove.Westfahl
S
6

I know that this issue was submitted and resolved approximately seven years ago, but there is a simpler solution now:

element.addEventListener('mousemove', function(event) {
 if(event.buttons == 1) {
  event.preventDefault();

  // Your code here!

 }
});

or for touch compatible devices:

element.addEventListener('touchmove', function(event) {
 if(event.touches.length == 1) {
  event.preventDefault();

  // Your code here!

 }
}

For more information on MouseEvent.buttons, click here to visit MDN Web Docs. Touch compatible devices, however, tend to listen to TouchEvents instead of MouseEvents. TouchEvent.touches.length achieves a similar effect to MouseEvent.buttons.

To provide an example, I used the following code to move an element I created. For moving an element, I used the 'mousemove' event's MouseEvent.movementX and MouseEvent.movementY to simplify the code. The 'touchmove' event does not have these so I stored the previous touch coordinates and cleared them on 'touchstart'. You can do something similar for the 'mousemove' event if desired, as the movementX and movementY values may vary across browsers.

document.addEventListener('DOMContentLoaded', () => {

 var element = document.getElementById('box');
 element.style.position = 'fixed';

 // MouseEvent solution.
 element.addEventListener('mousemove', function(event) {
  if(event.buttons == 1) {
   event.preventDefault();
   this.style.left = (this.offsetLeft+event.movementX)+'px';
   this.style.top = (this.offsetTop+event.movementY)+'px';
  }
 });

 // TouchEvent solution.
 element.addEventListener('touchstart', function(event) {
  /* Elements do not have a 'previousTouch' property. I create
     this property during the touchmove event to store and
     access the previous touchmove event's touch coordinates. */
  delete this.previousTouch;
 });
 element.addEventListener('touchmove', function(event) {
  if(event.touches.length == 1) {
   event.preventDefault();
   if(typeof this.previousTouch == 'object') {
    this.style.left = (this.offsetLeft+event.touches[0].pageX-this.previousTouch.x)+'px';
    this.style.top = (this.offsetTop+event.touches[0].pageY-this.previousTouch.y)+'px';
   }
   this.previousTouch = {
    x: event.touches[0].pageX,
    y: event.touches[0].pageY
   };
  }
 });
 
});
#box {
 width: 100px;
 height: 100px;
 padding: 1ch;
 box-sizing: border-box;
 background-color: red;
 border-radius: 5px;
 color: white;
}
<!DOCTYPE html>
<html>
 <head>
 </head>
 <body>
 
  <div id="box">Drag Me!</div>
  
 </body>
</html>

Hopefully this solution is helpful to you!

Sundsvall answered 20/6, 2022 at 0:26 Comment(1)
Cool! Unfortunately I've come to the conclusion that mousemove doesn't fire when manually scrolling an element's scrollbar with the mouse - only mousedown gets fired... for the few that needed mousemove for this reason.Fixer
B
1

The default behaviour will stop mouseMove and mouseUp from running, you can solve this by basically adding event.preventDefault() to the mousedown function

please ensure that you use the same parameter name passed in the mousedown function to trigger the preventDefault() if not it will not work , in the example below i passed event as the parameter to the mousedown function and then triggered preventDefault() by typing event.preventDefault()

let sliderImages =  Array.from(document.getElementsByClassName('slidess'));
const sliderPos = sliderImages.forEach( function (slide, index) {

    let mousePosStart, isDown = false;

    slide.addEventListener('mousedown', mousedown)
    slide.addEventListener('mousemove', mousemove)
    slide.addEventListener('mouseup', mouseup)

function mousedown(event) {
    if (isDown == false) {
        mousePosStart = event.pageX - this.offsetLeft;
        isDown = true;
        event.preventDefault();
    }
}

function mousemove(event) {
    if (isDown == true) {
        let mousePosMove = event.pageX - this.offsetLeft;
    }
}

function mouseup(event) {
    if (isDown === true) {
        isDown = false;
        let mousePosEnd = event.pageX - this.offsetLeft;
    }
}     

});

Becharm answered 11/11, 2021 at 11:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.