Here, in this tutorial I’ll show you how using jQuery .animate() method we can animatedly change text or background colors of an element. In addition, we’ll use the method to animatedly toggle the width and height of an element.
I designed a small demo to demonstrate how the effect works on a <div> element. To showcase the text color animation, the two-word phrase Animate Colors is placed inside the <div>.
Along with text color, we will change the background color and the border colors of the <div>. Each border’s color has to be animated individually.
The time set to change the colors of each elements is set as 700 milliseconds.
<head>
<title>jQuery UI Color Animation</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.9.1/jquery-ui.min.js"></script>
<style>
div {
padding:10px;
border:solid 1px #DEE8F1;
border-radius:5px;
-moz-border-radius:5px;
-webkit-border-radius:5px;
}
</style>
</head>
<body>
<div id="div" style="width:300px; text-align:center">Animate Colors</div>
<p><input type="button" id="btToggle" value="Change Colors" /></p>
</body>
<script>
var bChange = true;
$('#btToggle').click(function() {
// FORE COLOR.
if (bChange) $('#div').animate({ color: 'white', 'padding-left': '20px' }, 700);
else $('#div').animate({ color: '#000', 'padding-left': '0' }, 700);
// BACKGROUND COLOR.
if (bChange) $('#div').animate({ 'background-color': 'red' }, 700);
else $('#div').animate({ 'background-color': '#FFF' }, 700);
// BORDER COLOR.
if (bChange) $('#div').animate({ 'borderTopColor': '#000',
'borderBottomColor': '#000',
'borderLeftColor': '#000',
'borderRightColor': '#000'
}, 700);
else $('#div').animate({ 'borderTopColor': '#DEE8F1',
'borderBottomColor': '#DEE8F1',
'borderLeftColor': '#DEE8F1',
'borderRightColor': '#DEE8F1'
}, 700);
bChange = !bChange;
});
</script>To add a more dynamic visual effect alongside the color animation, I also applied the CSS padding-left property during the animation. This slightly expands the <div> toward the left, creating a smoother and more engaging transition.
$('#div').animate({ color: 'white', 'padding-left': '20px' }, 700);
Change "padding-left" to just "padding" and the see the effect.
Generate thousands of random colors instantly with our Random Color Generator 🚀.
