Two jQuery event handlers - execute code when both run

I want to run some code when two event handlers are triggered. I tried this as follows:

$('#box').mousedown(function(){ $(document).bind('mousemove',function(e){ // more code here }); }); 

But the code even works when I run mousedown once and move the mouse after that. I just want to execute the code when my mouse is down and moving. How can i achieve this?

0
source share
3 answers

Try to take this picture? Have a global variable that indicates whether or not the mouse pointer is located. When in mousedown on the #box element #box global variable is set to true. When they return, it will return 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 } }); }); 
+3
source

I think the problem you are facing is to understand how the event handlers work, after adding the event handler he will listen to his event.

Thus, your code will add an event handler to listen to mousedown , when dom is ready, as soon as it happens, it will add an event for mousemove - both event handlers are now registered in the document so that it does something for both independently.

What you want to do is remove the event handler for mousemove in the mouseup event. Thus, the document no longer listens for the mousemove event handler because it was deleted.

 $('#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 what happens, it will add a message under box .

+3
source

Use

 event.stop() 

or

 event.die() 

before using this event. Example:

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

Source: https://habr.com/ru/post/1411881/


All Articles