Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I trigger a mouseout event for two elements in jQuery?

Let's suppose I have two spearate divs, A and B, which overlap at a corner:

+-----+
|     |
|  A  |
|   +-----+
+---|     |
    |  B  |
    |     |
    +-----+

I want to trigger an event when the mouse leaves both A and B.

I tried this

$("#a, #b").mouseleave(function() { ... });

But this triggers the event if the mouse leaves either node. I want the event to be triggered once the mouse is not over either node.

Is there an easy way to do this? I had an idea that involved global variables keeping track of the mouse state over each div, but I was hoping for something more elegant.

like image 538
Peter Olson Avatar asked Dec 19 '11 05:12

Peter Olson


People also ask

What is Mouseout event in jQuery?

jQuery mouseout() Method The mouseout event occurs when the mouse pointer leaves the selected element. The mouseout() method triggers the mouseout event, or attaches a function to run when a mouseout event occurs.

What is the difference between Mouseout and Mouseleave?

This means that mouseleave is fired when the pointer has exited the element and all of its descendants, whereas mouseout is fired when the pointer leaves the element or leaves one of the element's descendants (even if the pointer is still within the element).

Is the Mouseout event fired?

The mouseout event is fired at an Element when a pointing device (usually a mouse) is used to move the cursor so that it is no longer contained within the element or one of its children.

In what situation will the event Mouseleave will take effect trigger?

The mouse leave event will be triggered whenever the mouse cursor leaves from the selected element and after the occurrence of the event, it implements a mouse leave event that has been attached to an event handler function to run.


1 Answers

I encounter this problem all the time, and my 'quick fix' if it fits what I'm doing is the following;

var timer;

$("#a, #b").mouseleave(function() {
    timer = setTimeout(doSomething, 10);
}).mouseenter(function() {
    clearTimeout(timer);
});


function doSomething() {
    alert('mouse left');
}

Fiddle : http://jsfiddle.net/adeneo/LdDBn/

like image 130
adeneo Avatar answered Oct 03 '22 09:10

adeneo