Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery detect mousedown inside an element and then mouseup outside the element

I have something similar to a drawing canvas, and I capture it's state on mouseup for undo purposes. The canvas isn't full screen, so you can draw with a brush and release outside the canvas. Something like this:

$("#element").mousedown(function(){
  $(document).mouseup(function(){
    //do something
  }); 
});

But this doesn't work of course. A plain $(document).mouseup doesn't work either, because I have many other UI elements and it saves the state each time you click on a UI element.

Any ideas?

like image 337
methodofaction Avatar asked Nov 30 '10 02:11

methodofaction


People also ask

What is Mousedown and mouseup?

MouseDown occurs when the user presses the mouse button; MouseUp occurs when the user releases the mouse button.

How do you trigger Mousedown?

The mousedown event occurs when the left mouse button is pressed down over the selected element. The mousedown() method triggers the mousedown event, or attaches a function to run when a mousedown event occurs. Tip: This method is often used together with the mouseup() method.

Is Mousedown the same as click?

Note: This differs from the click event in that click is fired after a full click action occurs; that is, the mouse button is pressed and released while the pointer remains inside the same element. mousedown is fired the moment the button is initially pressed.

How do I use Mousedown event?

To cause a MouseDown event for a form section to occur, press the mouse button in a blank area of the form section. The following apply to MouseDown events: If a mouse button is pressed while the pointer is over a form or control, that object receives all mouse events up to and including the last MouseUp event.


1 Answers

var isDown = false;

$("#element").mousedown(function(){
    isDown = true;
});

$(document).mouseup(function(){
    if(isDown){
        //do something
        isDown = false;
    }
}); 

For the sake of simplicity I put isDown in the global namespace. In production you would probably want to isolate the scope of that variable.

like image 154
mike Avatar answered Oct 02 '22 12:10

mike