While clicks are the most common interaction, jQuery allows you to track many other detailed mouse actions. From tracking when a user hovers over an element to detecting the exact moment a mouse button is pressed down, mouse events give you full control over the desktop user experience.
The hover() method is a unique jQuery function that combines two events:
**mouseenter** and **mouseleave**. It takes two functions as arguments.
$(selector).hover(
function() {
// Fires when mouse ENTERS
},
function() {
// Fires when mouse LEAVES
}
);
Example: Changing text on hover
$("#demo").hover(
function() { $(this).text("Hello!"); },
function() { $(this).text("Goodbye!"); }
);
Sometimes you need more granular control than just "hover." Here are the specific methods for each mouse state:
| Method | Trigger Moment |
|---|---|
mouseenter() |
Fires when the mouse pointer enters the element. |
mouseleave() |
Fires when the mouse pointer leaves the element. |
mousedown() |
Fires when the mouse button is pressed down. |
mouseup() |
Fires when the mouse button is released. |
You might have seen mouseover() in vanilla JavaScript. In jQuery,
**mouseenter** is usually preferred because it doesn't "bubble." This means it only
fires when entering the exact element you targeted, not when moving between its child
elements.
mouseenter() prevents your hover
animations from flickering when the user moves their mouse over text or icons inside the
main container.
A "click" is actually two events combined: a mousedown followed by a mouseup. Listening for these separately allows you to create interactive UI like buttons that "sink" into the page when pressed.
$("#pressBtn").mousedown(function() {
$(this).css("transform", "scale(0.95)");
});
$("#pressBtn").mouseup(function() {
$(this).css("transform", "scale(1)");
});
Here is how you might create a simple hover effect for a card-based layout:
$(".card").hover(
function() {
$(this).find(".details").stop().slideDown();
$(this).css("box-shadow", "0 10px 20px rgba(0,0,0,0.2)");
},
function() {
$(this).find(".details").stop().slideUp();
$(this).css("box-shadow", "none");
}
);
.stop() method before starting a hover
animation. This prevents animations from "queuing up" if a user repeatedly moves their
mouse in and out quickly.