Tutorial :jQuery: a question on events


How can I do with jQuery so that a mousemove event is active only if the left mouse button is being kept pressed, and as soon as the button gets released the mousemove event stops?


Here I bind the mousemove event on mousedown, and unbind it on mouseup. I used a cool feature in jQuery so there can be other mousemove events added to this selector, but only the one you want to unbind is removed. They are called Namespaced Events.

$("#yourdivid").mousedown(function(e){      if(e.which == 1){          $(this).bind('mousemove.coolnamespace', function(e){              // Your mousemove event          });      }  }).mouseup(function(e){      if(e.which == 1) $(this).unbind('mousemove.coolnamespace');  })  

Edit: I updated my answer to use the normalized field which. jQuery normalizes this to be 1 = Left, 2 = Middle, 3 = Right. The button value will be different depending on the browser.


The simple way is to keep a flag, which is set to true only while the left button is being kept pressed. It means that you have to set it to true when the left mouse button is pressed and reset it to false when released. Then you act on mousemove only if that flag is true.

It is not a jQuery specific solution, but a generic pattern for problems like this, so jQuery might provide a nicer solution.

You might need to take care of special cases, like losing input focus or the mouse cursor going outside that div while the left button is being kept pressed.


You bind the mousedown event and call mousemove inside of that function, and use the jQuery unbind event to get rid of the mousemove;

var $button = $("ELEMENT HERE");

        $button.mousedown(function(){              $(this).mousemove(function(){                  //Events here              });          }).mouseup(function(){              $(this).unbind("mousemove");          });  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »