Reputation: 1946
I want to do something continuously while the mouse is being held down, and stop it once is it released. So I have the following code:
var timeout;
var y;
$(document).mousemove(function(event){
y = event.pageY;
$(document).mousedown(function(){
timeout = setInterval(function(event){
// Do something with y
}, 100);
});
$(document).mouseup(function(){
clearInterval(timeout);
});
});
But this doesn't work! I can never stop doing something! the //Do something with y continuously runs!
What am I missing here?
Thanks
EDIT: The moousemove was a typo here, not in my code. My code is mousemove. It is still not working/
EDIT: The reason why I am using mousemove is because I want to continuously read the pageY. When I try to do that inside the setInterval(), it doesn't work. If I have it in the mousedown, it only reads it once. That is why I have it inside the mousemove()
Upvotes: 0
Views: 169
Reputation: 123739
You are making event binding on mouse move which will create numerous mousedown and mouseup events on document
. Even when you try to do a mouse down/mouseup; mouse move will get triggered and it goes on as a chain. Instead move them out of mousemove handler.
var timeout;
var y;
$(document).mousemove(function (event) {
y = event.pageY;
});
$(document).mousedown(function () {
timeout = setInterval(function (event) {
// Do something with y
console.log('mousedown ' + y);
}, 100);
});
$(document).mouseup(function () {
console.log('mouseup');
clearInterval(timeout);
});
You can verify this yourselves by placing a console.log in each event's call back entry point on your original code. You will be able to see the number of mousedown event increasing on every mousemove that you make. Check out this fiddle's console itself http://jsfiddle.net/eKy2T/
Upvotes: 3