Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Click event - get the target where the mousedown started instead of the mouseup

In a click event (attached to document) I want to figure out the target when the user started pressing the mousebutton.

Example:

  • User presses mousebutton on a custom popup
  • User moves the mouse outside the popup and let go

In that case the code below will return a target outside the popup, but I want to figure out if it started within the popup.

$(document).click(function(e)
{
    // will return the target during *releasing the mouse button*
    // but how to get the target where the *mouse press started*
    console.log(e.target); 
}

Of course I could track this manually by listening to mousedown and saving this within a variable - but I rather have something native, because:

  • less code
  • I might be missing edge cases

Both Jquery or vanilla JavaScript answers are good to me (but preference vanilla)

like image 576
Dirk Boer Avatar asked May 06 '19 16:05

Dirk Boer


People also ask

Do the mouse events click and Mousedown have the same functionality?

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.

Which of the following event triggers after Mousedown and then mouseup over the same element if the left mouse button was used?

click. Triggers after mousedown and then mouseup over the same element if the left mouse button was used. dblclick. Triggers after two clicks on the same element within a short timeframe.

What is Mousedown and mouseup?

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

Does mouseup fire before click?

Mouseup is always firing before click, despite this order.


1 Answers

You could use mousedown together with a mouseup function, and have them both saving their targets to a global variable, then compare them in an if statement.

let downTarget, upTarget;

$(document).mousedown(function(e) {
    downTarget = e.target;
});

$(document).mouseup(function(e) {
    upTarget = e.target;
});

if(upTarget === downTarget){ 
    *do stuff*
};
like image 102
Earle Poole Avatar answered Nov 15 '22 05:11

Earle Poole