p3nchan
p3nchan

Reputation: 1534

Color/background-color change animation in jQuery

I'm trying to do animation of color change in jQuery. But it failed.
JS Bin

$("#circle").click(function(){
    $(this).animate({
        backgroundColor: "#eee",
        width:"300px",
        height: "300px",
        borderRadius: "150px",
        }, 2000);
});

I know there's one similar answer on Stack Overflow, but it's years ago. So I ask again for potential newer answer to this problem. :)

Upvotes: 2

Views: 1225

Answers (2)

user4639281
user4639281

Reputation:

Vanilla Javascript and CSS animations

You can do this with css animations. However, it will not be animated on older browsers which do not support CSS animations, which can be a good thing.

In my experience computers which are using browsers old enough to not support the animations are generally slow enough that animations would be a detriment to the user experience, so I would recommend this method.

As well, CSS animations render smoother with less overhead than jQuery animations.

No external libraries required, not even jQuery

(function () {
    "use strict";
    document.getElementById("circle").onclick = function () {
        if (this.className.indexOf('clicked') < 0) this.className += ' clicked';
        else this.className = this.className.replace(/ clicked/g, '');
    };
})();
#circle {
    width: 100px;
    height: 100px;
    background: red;
    transition: all .4s linear;
}
#circle.clicked {
    background: #eee;
    width: 300px;
    height: 300px;
    border-radius: 50%;
}
<div id="circle"></div>

Upvotes: 1

Ben
Ben

Reputation: 9001

You need to use jQuery UI as well as jQuery, as jQuery alone doesn't support colour animations.

jQuery UI

JS Bin

Upvotes: 3

Related Questions