Leff
Leff

Reputation: 1320

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);

Upvotes: 1

Views: 765

Answers (3)

Action Coding
Action Coding

Reputation: 830

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

Upvotes: 0

antoni
antoni

Reputation: 5546

Michael McCoy is totally right in his comment. I would do the same as you will also benefit from GPU acceleration if you use CSS and it will make your code lighter.

This apart, your code has 2 errors:

  • missing i++
  • missing var i

_

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

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

Anyway, drop this idea.

So to add class just do $('.top-barz').addClass('changedColor');

and in css:

.top-barz {
  background-color: rgba(36,36,36,.1);
  -webkit-transition: 1s;
  -o-transition: 1s;
  transition: 1s;
}
.top-barz.changedColor {
  background-color: rgba(36,36,36,1);
}

Upvotes: 0

Charles Guo
Charles Guo

Reputation: 170

You may consider the fadeIn function of jQuery.

$('.top-barz').fadeIn(10000);

Upvotes: 1

Related Questions