ngplayground
ngplayground

Reputation: 21627

jQuery fade background color of a header bar in when scrolled down

I'm trying to fade the background of a header in to white but when I try using some jQuery to animate the fade of the background color, it just won't work.

jQuery

var windw = this;
$.fn.followTo = function ( pos ) {
    var $this = this,
        $window = $(windw);

    $window.scroll(function(e){
        if ($window.scrollTop() > pos) {
            $this.animate({'backgroundColor':'rgba(255,255,255,1)'},400);
            console.log($this.css('backgroundColor'));
            console.log(pos);
        } else if ($window.scrollTop() == 0) {
            $this.animate({'backgroundColor':'rgba(255,255,255,0)'});
            console.log($this.css('backgroundColor'));
            console.log(pos + ' at the top');
        } else {
            $this.animate({'backgroundColor':'rgba(255,255,255,0)'});
            console.log($this.css('backgroundColor'));
        }
    });
};

$('.home-header-main').followTo(86);

jsFiddle Demo

Help is appreciated

Upvotes: 0

Views: 484

Answers (2)

adeneo
adeneo

Reputation: 318242

Just to animate the opacity of the background color, you don't really need a color animation plugin, you can use CSS transitions for newer browsers, but if you have to support browsers that don't support CSS3 you can use the step() method in jQuery's animate :

$.fn.followTo = function ( pos ) {
    return this.each(function() {

        var $this = $(this),
            $window = $(window),
            flag = true;

        $this[0].x = 1;

        $window.on('scroll', function(e){
            if ($window.scrollTop() > pos && flag) {
                flag = !flag
                anim($this, 0);
            }else if ($window.scrollTop() < pos && !flag){
                flag = !flag
                anim($this, 1);
            }

        });
    });

    function anim(elem, val) {
        elem.stop(true, false).animate({
          x : val
        },
        {
          step: function(now, fx) {
              $(fx.elem).css({backgroundColor : 'rgba(255,255,255,'+now+')'});
          },
          duration: 4000
        });
    }
};

$('.home-header-main').followTo(86);

FIDDLE

Upvotes: 0

Paul Sham
Paul Sham

Reputation: 3205

You can animate rgba using jQuery with the help of plugins, but I would let CSS3 handle all of this using CSS transitions.

Example:

body {
   background-color: rgba(255,255,255,1);
   -webkit-transition: background-color 0.4s linear; 
      -moz-transition: background-color 0.4s linear; 
        -o-transition: background-color 0.4s linear; 
           transition: background-color 0.4s linear; 
}

.bg-faded {
   background-color: rgba(255,255,255,0);
}

Then, you can use Javascript to toggle the class.

Upvotes: 2

Related Questions