Leff Leff - 1 month ago 14
jQuery Question

Javascript - changing background color opacity with time interval

I am trying to add the background color to a

.top-barz
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)
to
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 + ')');
}
}

clearInterval(topBar);

Answer

Here is some sample code to get you started

JQuery

$('.button').on('click', function() {
 $('.top-barz').addClass('new-color');
});

CSS

.top-barz {
 background-color:#000;
 -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 {
 background-color:#eee;
}

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

EDIT

Here is the Fiddle

Seems to be working fine in chrome on my end