jQuery UI Color Animation - Change Background Color Animatedly using jQuery

← PrevNext →

For years, web developers have used JavaScript for creating special effects on elements on a web page. Talking about special effects, color animation comes to our mind. Animations, which include changing the color of text or background color, etc.
See this demo

Here, in this article 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.

We have designed a small demo to show how it works on a <div> element. To animate the color of the text, a two word text (‘Animate Colors’) is written 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.

The CSS and Markup
    <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>
        div {
            border:solid 1px #DEE8F1; 
    <div id="div" style="width:300px; text-align:center">Animate Colors</div>
    <p><input type="button" id="btToggle" value="Change Colors" /></p>
The 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);

        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;
See this demo

Just to add a little more special effects along with the colors, I have added CSS padding-left property while animating the color of the text. It actually expands the <div> a slightly towards the left.

$('#div').animate({ color: 'white', 'padding-left': '20px' }, 700);

Try changing padding-left to just padding and the see the effect.

← PreviousNext →