开发者

Two jQuery Event Handlers - execute code when both are fired

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 eve开发者_如何转开发n 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?


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.


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
        }
    });
});


Use the

event.stop()

or

event.die()

snippet before use the event. Example:

$("#mybutton").unbind("click");
$("#mybutton").die();
$("#mybutton").click(function(){ alert("Hy mate!");});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜