Mouse & Hover Events
Respond to the pointer entering, leaving, and moving over elements.
Syntax
$(selector).hover(inHandler, outHandler);Mouse events let you build hover effects and interactive UI.
mouseenter— pointer enters the element.mouseleave— pointer leaves the element.mousemove— pointer moves within it.
The older .hover(inFn, outFn) shortcut binds enter and leave together.
Example
Loading editor…
Press Run to see the result.
When to use it
- A navigation menu reveals a dropdown on mouseenter and hides it on mouseleave using .hover().
- A product card scales up its image when the pointer enters and scales back on leave.
- A tooltip component shows contextual text near the cursor on mouseenter and removes it on mouseleave.
More examples
Highlight a card on hover
.hover(over, out) is shorthand for binding mouseenter and mouseleave with two separate callbacks.
<div class="card" style="padding:20px;display:inline-block;">Hover me</div>
<script>
$(function () {
$(".card").hover(
function () { $(this).css("background", "#e8f4fd"); },
function () { $(this).css("background", ""); }
);
});
</script>Toggle class on mouseenter/leave
Using separate .on() calls makes it clear which class is added on enter and removed on leave.
<button class="fancy-btn">Submit</button>
<script>
$(function () {
$(".fancy-btn")
.on("mouseenter", function () { $(this).addClass("hovered"); })
.on("mouseleave", function () { $(this).removeClass("hovered"); });
});
</script>Show tooltip near cursor with mousemove
mousemove updates the tooltip position using event coordinates so it follows the pointer around the element.
<div id="target" style="padding:30px;background:#eee;">Move mouse here</div>
<div id="tip" style="display:none;position:fixed;background:#333;color:#fff;padding:4px 8px;">Tooltip</div>
<script>
$(function () {
$("#target")
.on("mouseenter", function () { $("#tip").show(); })
.on("mousemove", function (e) { $("#tip").css({ top: e.clientY + 12, left: e.clientX + 12 }); })
.on("mouseleave", function () { $("#tip").hide(); });
});
</script>
Discussion