jQuery mouseout: Main Tips
- The jQuery
.mouseout()
method attaches an event handler tomouseout
event, or triggers the event. - The
mouseout
event occurs when the mouse pointer exits the element. - Unlike a similar .mouseleave() method,
.mouseout()
reacts to event bubbling.
Usage of .mouseout() Method
The .mouseout()
method in jQuery attaches an event handler, executing a function when the mouseout
event occurs, or triggers the event.
In the example below, you will notice no changes apply as you move your cursor on the paragraph, but the background color changes as the cursor moves away:
Example
$("p").mouseout(() => {
$("p").css("background-color", "green");
});
The .mouseleave() method can be used as an alternative for .mouseout()
in jQuery. However, you must keep in mind their behavior differs when the elements have descendants:
Example
var i = 0;
$( "div.overout" )
.mouseover(function() {
$( "p:first", this ).text( "mouse over" );
$( "p:last", this ).text( ++i );
})
.mouseout(function() {
$( "p:first", this ).text( "mouse out" );
});
var n = 0;
$( "div.enterleave" )
.mouseenter(function() {
$( "p:first", this ).text( "mouse enter" );
$( "p:last", this ).text( ++n );
})
.mouseleave(function() {
$( "p:first", this ).text( "mouse leave" );
});
Use this syntax to trigger the mouseout
event:
$("selector").mouseout();
Bind the event handler by specifying the function
:
$("selector").mouseout(function);