We can use the jQuery mouseout method to run a function when a user moves their mouse out of a div. To do this we can add a function call to the mouseout() method.
$("#div1").mouseout(function() {
//The user has moved their mouse out of #div1
});
Another way this can be done is to use the .on() method:
$("#div1").on("mouseout", function() {
//The user has moved their mouse out of #div1
});
The jQuery mouseout() method is very similar to the mouseleave() method, the main difference being that the mouseout method will trigger when you mouse out of any child elements of the div, while the mouseleave method will not. We will show this in the example below.
An example using the jQuery mouseout method
In this example, we will have 3 divs set up next to each other. One div will be empty, and the other two will have a child element that takes up half of the div. We will add some CSS to float the divs next to each other and display the text in the center.
Here is the HTML setup:
div1
mouseout method
mouseleave method
When the user moves their mouse out of each div, we will generate a random color and then change the background color of the div.
For the third div, we will use the mouseleave method to show how it differs from the mouseout method.
Here is the JavaScript code:
function genRandomColor() {
var letters = '0123456789ABCDEF';
var randomColor = '#';
for (var i = 0; i < 6; i++) {
randomColor += letters[Math.floor(Math.random() * 16)];
}
return randomColor;
}
$("#div1").mouseout(function() {
$('#div1').css("background-color", genRandomColor());
});
$("#div2").mouseout(function() {
$('#div2').css("background-color", genRandomColor());
});
$("#div3").mouseleave(function() {
$('#div3').css("background-color", genRandomColor());
});
The final code and output for this example of using the jQuery mouseout() method is below:
Code Output:
Full Code:
div1
mouseout method
mouseleave method
<script>
function genRandomColor() {
var letters = '0123456789ABCDEF';
var randomColor = '#';
for (var i = 0; i < 6; i++) {
randomColor += letters[Math.floor(Math.random() * 16)];
}
return randomColor;
}
$("#div1").mouseout(function() {
$('#div1').css("background-color", genRandomColor());
});
$("#div2").mouseout(function() {
$('#div2').css("background-color", genRandomColor());
});
$("#div3").mouseleave(function() {
$('#div3').css("background-color", genRandomColor());
});
</script>
Hopefully this article has been useful to help you understand how to use the jQuery mouseout() method.