Reputation: 1
I want to run some code when two event handlers are both triggered. I've tried it like this:
$('#box').mousedown(function(){
$(document).bind('mousemove',function(e){
// more code here
});
});
But the code even works when I trigger mousedown once and move my mouse after that. I only want to execute the code when my mouse is down and it's moving. How can I achieve that?
Upvotes: 0
Views: 258
Reputation: 658
Use the
event.stop()
or
event.die()
snippet before use the event. Example:
$("#mybutton").unbind("click");
$("#mybutton").die();
$("#mybutton").click(function(){ alert("Hy mate!");});
Upvotes: 0
Reputation: 6866
Try giving this a shot? Have a global variable that indicates whether the mouse is down or not. When they mousedown on the #box
element the global variable is set to true. When they mouseup it's set back to false. See a live example here.
$(document).ready(function(){
var mouseDown = false;
$("#box").mousedown(function(){
mouseDown = true;
});
$(document).mouseup(function(){
mouseDown = false;
});
$(document).mousemove(function(){
if (mouseDown){
//do your stuff here
}
});
});
Upvotes: 3
Reputation: 9719
I think the problem you are having is with your understanding of the way the event handlers work, once you have added an event handler it will listen out for its event.
So your code will add an event handler to listen for mousedown
when the dom is ready, once it occurs it will add an event for mousemove
- the document now has both event handlers registered so it will do stuff for both independently.
What you want to do, is remove the event handler for the mousemove
on the mouseup
event. That way the document now no longer listens to the mousemove
event handler because its been removed.
$('#box').mousedown(function(){
$(document).bind('mousemove',function(e){
// Do something:
});
});
$(document).mouseup(function(){
$(document).unbind('mousemove');
});
Here is a simple example, so you can see whats happening it will add a message under the box
.
Upvotes: 3