The Hover Event
In this page:
Basic Hover
.hover() takes two functions and pairs them together -- the first runs when the mouse enters the element, the second when it leaves. It's essentially shorthand for binding mouseenter and mouseleave separately.
Example: Basic Hover
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<div id="box">Hover me</div>
<script>
$("#box").hover(function() {
console.log("Mouse entered");
}, function() {
console.log("Mouse left");
});
</script>
</body>
</html>
Hover Styling
Passing a style change into hover's enter/leave functions, like changing background-color, is a quick way to give an element visual feedback without writing separate CSS :hover rules.
Example: Hover Styling
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<div id="box">Hover me</div>
<script>
$("#box").hover(function() {
$(this).css("background-color", "yellow");
}, function() {
$(this).css("background-color", "");
});
</script>
</body>
</html>
Hover Messages
Showing a short message or tooltip on hover-in and clearing it on hover-out is a common pattern for lightweight, JavaScript-driven help text.
Example: Hover Messages
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<div id="box">Hover me</div><p id="msg"></p>
<script>
$("#box").hover(function() {
$("#msg").text("You are hovering!");
}, function() {
$("#msg").text("");
});
</script>
</body>
</html>
Hover and Classes
Adding a class in the enter function and removing it in the leave function keeps styling logic in your CSS while jQuery just toggles which rules apply, which is usually cleaner than inline style changes.
Example: Hover and Classes
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<style>
.highlighted { background: yellow; }
</style>
</head>
<body>
<div id="box">Hover me</div>
<script>
$("#box").hover(function() {
$(this).addClass("highlighted");
}, function() {
$(this).removeClass("highlighted");
});
</script>
</body>
</html>
Hover with Images
Swapping an image's src attribute (or updating its alt text) between the two hover functions is a classic technique for simple image-based hover effects like button states.
Example: Hover with Images
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<img id="pic" src="button-off.png" alt="Button">
<script>
$("#pic").hover(function() {
$(this).attr("src", "button-on.png");
}, function() {
$(this).attr("src", "button-off.png");
});
</script>
</body>
</html>
Chapter Quiz — Complete all 11 topics to unlock
0/11 topics done
Complete these topics first: