Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check if the mouse is over an element in jQuery?

People also ask

How do you know if a mouse is over an element?

Use document. elementFromPoint(x, y) method to get the element content on that position when mouse pointer moves over.

Is mouse over jQuery?

jQuery mouseover() MethodThe mouseover() method triggers the mouseover event, or attaches a function to run when a mouseover event occurs. Note: Unlike the mouseenter event, the mouseover event triggers if a mouse pointer enters any child elements as well as the selected element.

When mouse pointer is over the particular element it is known as?

In computing, a mouseover , mouse hover or hover box is a graphical control element that is activated when the user moves or hovers the pointer over a trigger area, usually with a mouse, but also possible with a digital pen. Mouseover control elements are common in web browsers.

Is triggered when the mouse moves over an element?

mouseover: The onmouseover event triggers when the mouse pointer enters an element or any one of its child elements. mouseenter: The onmouseenter event is triggered only when the mouse pointer hits the element.


This code illustrates what happytime harry and I are trying to say. When the mouse enters, a tooltip comes out, when the mouse leaves it sets a delay for it to disappear. If the mouse enters the same element before the delay is triggered, then we destroy the trigger before it goes off using the data we stored before.

$("someelement").mouseenter(function(){
    clearTimeout($(this).data('timeoutId'));
    $(this).find(".tooltip").fadeIn("slow");
}).mouseleave(function(){
    var someElement = $(this),
        timeoutId = setTimeout(function(){
            someElement.find(".tooltip").fadeOut("slow");
        }, 650);
    //set the timeoutId, allowing us to clear this trigger if the mouse comes back over
    someElement.data('timeoutId', timeoutId); 
});

A clean and elegant hover check:

if ($('#element:hover').length != 0) {
    // do something ;)
}

WARNING: is(':hover') is deprecated in jquery 1.8+. See this post for a solution.

You can also use this answer : https://stackoverflow.com/a/6035278/8843 to test if the mouse is hover an element :

$('#test').click(function() {
    if ($('#hello').is(':hover')) {
        alert('hello');
    }
});

Set a timeout on the mouseout to fadeout and store the return value to data in the object. Then onmouseover, cancel the timeout if there is a value in the data.

Remove the data on callback of the fadeout.

It is actually less expensive to use mouseenter/mouseleave because they do not fire for the menu when children mouseover/mouseout fire.