Leff Leff - 1 year ago 135
jQuery Question

Javascript - changing background color opacity with time interval

I am trying to add the background color to a

element when I click on another element, but I would like to make that as an animation in duration of 1s. I am pretty new to javascript and not sure how to do that?

I would like to animate from change opacity of
rgba(36,36,36, .1)
rgba(36,36,36, 1)

I have come up with this code and put it into my on click function, but this is obviously not working:

var topBar = setInterval(function(){ topBarBackground() }, 1000);

function topBarBackground() {
for (var i = 1; i <= 9; i++) {
$('.top-barz').css('background-color', 'rgba(36,36,36,.' + i + ')');


Answer Source

Here is some sample code to get you started


$('.button').on('click', function() {


.top-barz {
 -webkit-transition: background-color 1s linear;
 -moz-transition: background-color 1s linear;
 -o-transition: background-color 1s linear;
 -ms-transition: background-color 1s linear;
 transition: background-color 1s linear;

.top-barz.new-color {

Obviously you would change the colors to whatever color you want for your design.


Here is the Fiddle

Seems to be working fine in chrome on my end

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download