A
A
Alexander2016-07-18 11:16:36
JavaScript
Alexander, 2016-07-18 11:16:36

How to determine if the mouse is over an element at the moment?

It is necessary to determine whether the mouse is over the given element right at the moment. Hover() is not suitable as it initializes the .mouseenter() and .mouseleave() events and I need to check right now (the mouse may already be on the element).

Answer the question

In order to leave comments, you need to log in

5 answer(s)
N
nikosias, 2016-07-18
@nikosias

var info;
$('body').mousemove(function(e){
  if (info !==e.target){
  	console.log(e.target);
    info =e.target;
  }
});

R
Rafael™, 2016-07-18
@maxminimus

What if I don't have a mouse on my iPad?

D
Dmitry Vapelnik, 2016-07-18
@dvapelnik

you need to handle events onmouseoverand onmouseout(if I'm not mistaken in the names) and write some attribute to the element: the mouse went to the element - the attribute was recorded, the mouse left - the attribute was removed. but you will have a lot of such elements due to the fact that the event pops up and therefore, in order to find the element on which the mouse is now, you will need to find the element that has the attribute set, but it does not have children with the attribute set
yes, the speed of work will be desirable better with a large DOM tree, but if your DOM tree does not change, then you can mirror your DOM tree to some data structure that you will already work with directly. if the DOM tree changes, you will need to synchronize this structure of yours with the DOM tree

A
AnjeyTsibylskij, 2016-07-18
@AnjeyTsibylskij

You can actually keep track of whether the cursor is now on the desired element. Here's what it looks like in practice
*See the result in the console.

N
napa3um, 2016-07-18
@napa3um

DOM receives information about the position of the mouse exclusively by events, there is no separate API for accessing mouse coordinates. If the browser does not send mouse events when an element is hit by a stationary mouse cursor, then there is nothing to be done from the JS sandbox. (If it sends, then https://developer.mozilla.org/en-US/docs/Web/API/D... will help determine the element at the cursor coordinates.)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question