views:

158

answers:

3

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?

+1  A: 

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.

fviktor
+5  A: 

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.

Doug Neiner
A: 
Vibhu