jQuery: How to execute code when multiple events are performed ie. mousemove whilst mouse is clicked.?

Question by dfgs: jQuery: How to execute code when multiple events are performed ie. mousemove whilst mouse is clicked.?
Basically I need some code to execute when the mouse is clicked and being dragged around. With my current code the code executes when the mouse is down and when the mouse is moved but then when the mouse click is released the code continues to execute so I have included an if statement. I’m sure there is a much more efficient way of doing this so any help would be really appreciated 🙂

P.S another problem I am having is say the user clicks on the element, then lets go the mouseup (“//more code”) gets executed once but if the user then clicks again and lets go it will be executed twice and if they select and deselect again 3 times etc.

As you can probably tell I am a bit of a jQuery noob! 😛

Current code:

$ (‘element’).mousedown(function(event){
mouseDown = true;
$ (document).mousemove(function(event2){
if(mouseDown){
//code goes here
}
}).mouseup(function(){
mouseDown = false;
//more code
});
});

Best answer:

Answer by Ratchetr
You need to call unbind for mousemove and mouseup inside your mouseup handler (see link).
Replace mouseDown = false with:
$ (document).unbind(‘mousemove’);
$ (document).unbind(‘mouseup’);

However, that form of unbind will remove *all* mousemove/mouseup event handlers on the document. This might not be what you want.
See the ‘Using Namespaces’ section in link for an easy way to solve this. Note, to use namespaces, you’ll need to replace your .mousemove and .mouseup calls with calls to bind.

Add your own answer in the comments!

Revisions

There are no revisions for this post.

Tags: , , , , , , , , ,

No comments yet.

Leave a Reply