0

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

ngplayground
  • 20,365
  • 36
  • 94
  • 173

2 Answers2

2

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.

Community
  • 1
  • 1
Paul Sham
  • 3,185
  • 2
  • 24
  • 31
0

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

adeneo
  • 312,895
  • 29
  • 395
  • 388