We can use the jQuery mouseover 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 mouseover() method.

$("#div1").mouseover(function() {
  //The user has moved their mouse into #div1
});

Another way this can be done is to use the .on() method:

$("#div1").on("mouseover", function() {
    //The user has moved their mouse into #div1
});

The jQuery mouseover() method is very similar to the mouseenter() method, the main difference being that the mouseover method will trigger when you mouse over any child elements of the div, while the mouseenter method will not. We will show this in the example below.

An example using the jQuery mouseover 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
mouseover method
mouseenter 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 mouseenter method to show how it differs from the mouseover 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").mouseover(function() {
  $('#div1').css("background-color", genRandomColor());
});
$("#div2").mouseover(function() {
  $('#div2').css("background-color", genRandomColor());
});
$("#div3").mouseenter(function() {
  $('#div3').css("background-color", genRandomColor());
});

The final code and output for this example of using the jQuery mouseover() method is below:

Code Output:

div1
mouseover method
mouseenter method

Full Code:


div1
mouseover method
mouseenter 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").mouseover(function() { $('#div1').css("background-color", genRandomColor()); }); $("#div2").mouseover(function() { $('#div2').css("background-color", genRandomColor()); }); $("#div3").mouseenter(function() { $('#div3').css("background-color", genRandomColor()); }); </script>

Hopefully this article has been useful to help you understand how to use the jQuery mouseover() method.

Categorized in:

jQuery,

Last Update: February 26, 2024