santBart
santBart

Reputation: 2496

jquery mouseclick event

I am quite new to jquery and looking for event that handles mouse down event. Over now I have found and use something like:

 $("#canva").live('mousedown mousemove mouseup', function(e){ ....

but it fires function(e) even when mouse is over canvas element (both when the left button is clicked or not).

I am looking forward to event that will be fired in every change of coordinates above #canva element and when my mouses button is clicked. Releasing left mouse button should cause end of this event.

Upvotes: 2

Views: 12131

Answers (1)

pikappa
pikappa

Reputation: 366

One way to do this would be to create a global variable and to modify its value when the user clicks over the element as such:

var mouseIsDown = false;

$('#mycanvas').on('mousedown', function () {mouseIsDown = true});
$('#mycanvas').on('mouseup', function () {mouseIsDown = false});

Now all you have to do is to bind 'mousemove' to the function you want to fire and simply appending a conditional to the body of the function that checks the state of the left click and escapes if necessary.

function fireThis(e) {
// if the user doesn't have the mouse down, then do nothing
if (mouseIsDown === false)
     return;

// if the user does have the mouse down, do the following
// enter code here
// ....
// ....
}

// bind mousemove to function
$('#mycanvas').on('mousemove', fireThis);

Now, if the user were to click inside the element and then drag the mouse outside the element before releasing, you'll notice that 'mouseup' will never get triggered and the variable mouseIsDown will never be changed back to false. In order to get around that, you can either bind 'mouseout' to a function that resets mouseIsDown or bind 'mouseup' globally as such:

$('#mycanvas').on('mouseout', function () {mouseIsDown = false});

OR

$(document).on('mouseup', function () {mouseIsDown = false});

Here's an example: http://jsfiddle.net/pikappa/HVTWb/

Upvotes: 2

Related Questions