Javascript

jQuery hover animation

jQuery Hover Animation: A Simple Guide

✅ What Is hover() in jQuery?

The .hover() method in jQuery lets you define two behaviors:

  • One when the mouse enters an element

  • One when the mouse leaves the element

Syntax:

js
$(selector).hover(
function() {
// mouse enters
},
function() {
// mouse leaves
}
);

Example: Animate a Box on Hover

HTML

html
<div id="box">Hover over me!</div>

<!-- jQuery CDN -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

CSS (optional styling)

html
<style>
#box {
width: 200px;
height: 200px;
background-color: steelblue;
color: white;
text-align: center;
line-height: 200px;
transition: background-color 0.3s ease;
}
</style>

⚙️ jQuery Hover Animation

js
$('#box').hover(
function () {
// Mouse enters
$(this).animate({
width: '250px',
height: '250px',
opacity: 0.7
}, 300);
},
function () {
// Mouse leaves
$(this).animate({
width: '200px',
height: '200px',
opacity: 1
}, 300);
}
);

Output

When you hover over the box:

  • It smoothly grows in size

  • Its opacity fades slightly

  • When you move the mouse away, it returns to normal


Bonus: Change Background on Hover

You can also combine .css() or .toggleClass() with hover():

js
$('#box').hover(
function () {
$(this).css('background-color', 'crimson');
},
function () {
$(this).css('background-color', 'steelblue');
}
);

✅ Summary

Method Description
.hover() Triggers two functions: enter + leave
.animate() Smoothly changes numeric CSS properties
.css() Instantly changes CSS styles

Leave a Reply

Your email address will not be published. Required fields are marked *