Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
How to animate a change in background color using jQuery on mouseover?
To change background color with animation, use the mouseenter and mouseleave events. The background color changes smoothly when you place the mouse cursor over an element using jQuery's animate() method.
For basic color change without animation, you can use the css() method ?
mouseenter: function(){
$(this).css("background-color", "gray");
}
However, to create smooth animated transitions, jQuery's animate() method provides better visual effects. The mouse cursor interaction is applied to the following element ?
<p class="my">Move the mouse pointer to animate the background color change.</p>
Example
You can try to run the following code to learn how to animate a change in background color on mouseover ?
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<style>
.my {
padding: 20px;
background-color: lightblue;
border: 1px solid #ccc;
cursor: pointer;
transition: background-color 0.3s ease;
}
</style>
<script>
$(document).ready(function(){
$(".my").on({
mouseenter: function(){
$(this).css("background-color", "gray");
},
mouseleave: function(){
$(this).css("background-color", "lightblue");
}
});
});
</script>
</head>
<body>
<p class="my">Move the mouse pointer to animate the background color change.</p>
</body>
</html>
In this example, the mouseenter event changes the background to gray when the mouse hovers over the element, while mouseleave restores the original light blue background. The CSS transition property creates the smooth animation effect.
Conclusion
Using jQuery's mouse events with CSS transitions provides an effective way to animate background color changes, creating smooth and visually appealing hover effects for web elements.
