0

So I've been looking far and wide for ways to animate my header to change background color when I scroll further then 550px.

Here is the code:

$(function(){
$('header').data('size','big');
});

$(window).scroll(function(){
var $header = $('header');
if ($('body').scrollTop() > 550) {
    if ($header.data('size') == 'big') {
        $header.data('size','small').stop().animate({
            'background','#444349'
            }, 'slow');
    }
} else {
    if ($header.data('size') == 'small') {
        $header.data('size','big').stop().animate({
            'background','transparent'
        }, 'slow');
    }  
}
});
Nocraze
  • 25
  • 2
  • 1
    You need to animate `backgroundColor` and not `background`, using jQueryUI, but I would be surprised if `transparent` is a numeric color value it can animate to. What is your default/page background color? (animate to that) – iCollect.it Ltd Jan 07 '15 at 12:30
  • 1
    By default, jQuery doesn't support color animation, use a specific plugin for that or better toggle a class and use CSS transition or even better you could target the data attribute specific value of header and set background color to that, still using some CSS transition. **As a side note**, you should use `$(window).scrollTop()` to support all browsers – A. Wolff Jan 07 '15 at 12:30
  • possible duplicate. http://stackoverflow.com/questions/8755887/jquery-change-background-color-user-scroll . With different classes you can animate with css. – Luís P. A. Jan 07 '15 at 12:31
  • you need to animate the opacity of the `backgroundColor` using the `rgba(r, g, b, a)` syntax, jQuery supports those as well – David Fregoli Jan 07 '15 at 12:37

1 Answers1

1

Why not use CSS to animate the header?

CSS:
header {
    background: transparent;
    transition: background .6s; /* 'slow' is 600ms */
}

header.foobar {
    background: #444349;
}
JavaScript:
$(window).scroll(function(){
    if($('body').scrollTop() > 550){
        $('header').addClass('foobar');
    }else{
        $('header').removeClass('foobar');
    }
});

Check it out here.

Stephan
  • 360
  • 3
  • 9