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)
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)
Share Improve this question asked May 6, 2019 at 16:56 Dirk BoerDirk Boer 9,17313 gold badges71 silver badges123 bronze badges 1-
perhaps use the
mouseup
event if you don't mind it being fired earlier – junvar Commented May 6, 2019 at 16:58
2 Answers
Reset to default 5You could use mousedown together with a mouseup function, and have them both saving their targets to a global variable, then pare 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*
};
just use the event mousedown
instead click like
$(document).mousedown(function(e)
{
console.log(e.target);
}
also has another event that verifies if the mouse is over that is the mouseover