We can use the jQuery mouseenter method to run a function when a user moves their mouse over a div. To do this we can add a function call to the mouseenter() method.
$("#div1").mouseenter(function() {
//The user has moved their mouse into #div1
});
Another way this can be done is to use the .on() method:
$("#div1").on("mouseenter", function() {
//The user has moved their mouse into #div1
});
The jQuery mouseenter() method is very similar to the mouseover() method, the main difference being that the mouseover method will trigger when you mouse over child elements of the div, while the mouseenter method will not. We will show this in the example below.
An example using the jQuery mouseenter 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
mouseenter method
mouseover method
When the user moves their mouse into 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 mouseover method to show how it differs from the mouseenter 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").mouseenter(function() {
$('#div1').css("background-color", genRandomColor());
});
$("#div2").mouseenter(function() {
$('#div2').css("background-color", genRandomColor());
});
$("#div3").mouseover(function() {
$('#div3').css("background-color", genRandomColor());
});
The final code and output for this example of using the jQuery mouseenter() method is below:
Code Output:
Full Code:
div1
mouseenter method
mouseover 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").mouseenter(function() {
$('#div1').css("background-color", genRandomColor());
});
$("#div2").mouseenter(function() {
$('#div2').css("background-color", genRandomColor());
});
$("#div3").mouseover(function() {
$('#div3').css("background-color", genRandomColor());
});
</script>
Hopefully this article has been useful to help you understand how to use the jQuery mouseenter() method.