How to run a code on hover event in jQuery ?
To run a code on hover event in jQuery, you can use the .hover()
method. This method takes two functions as arguments, one for the mouseenter
event and one for the mouseleave
event. Here's an example:
<div id="myDiv">Hover over me</div>
$(document).ready(function() {
$('#myDiv').hover(function() {
// Code to run on mouseenter
$(this).css('background-color', 'red');
}, function() {
// Code to run on mouseleave
$(this).css('background-color', 'white');
});
});
In this example, when the mouse enters the #myDiv
element, its background color is changed to red, and when the mouse leaves the element, its background color is changed back to white.
Alternatively, you can use the .mouseenter()
and .mouseleave()
methods separately. Here's an example:
$(document).ready(function() {
$('#myDiv').mouseenter(function() {
// Code to run on mouseenter
$(this).css('background-color', 'red');
});
$('#myDiv').mouseleave(function() {
// Code to run on mouseleave
$(this).css('background-color', 'white');
});
});
This code does the same thing as the previous example, but separates the mouseenter
and mouseleave
events into separate functions.