how to implement mousemove while mouseDown pressed js
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');});
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!)
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; }}
});