2

I'm trying to change my navigation background color with an animation but it's not working.

I currently got the following code:

//NAV

    $(document).ready(function(){
      $(window).scroll(function() {
        if ($(document).scrollTop() > 50) {
          $("#posnav").animate({
          backgroundColor: "#aa0000"
        }, 1000 );
        } else {
          $("#posnav").animate({
          backgroundColor: "#transparant"
        }, 1000 );
        }
      });
    });
empiric
  • 7,825
  • 7
  • 37
  • 48
Jarno D
  • 23
  • 2
  • To animate colors you either need the [jQuery Color plugin](https://github.com/jquery/jquery-color) or [jQuery UI](https://jqueryui.com/), as of my knowlegde it is not supported in the jQuery core – empiric Dec 14 '16 at 17:19
  • 2
    Possible duplicate of [jQuery animate backgroundColor](http://stackoverflow.com/questions/190560/jquery-animate-backgroundcolor) – empiric Dec 14 '16 at 17:19
  • You got a typo in "navigation" in your title. – GillesC Dec 14 '16 at 17:25

1 Answers1

0

As stated above, jQuery .animate() only works with numeric properties such as width, height, and margins, but NOT colour -- in which case you need a plugin. See: http://api.jquery.com/animate/

You can, however, use the CSS transition property to achieve similar effect.

// CSS

#posnav { 
    background-color: transparent;
    transition: background-color 0.5s ease;
}
#posnav.scrolled {
    background-color: #aa0000; 
}

// JS:

$(document).ready(function(){
  $(window).scroll(function() {
    if ($(document).scrollTop() > 50) {
      $('#posnav').addClass('scrolled');
    } else {
      $('#posnav').removeClass('scrolled');
    }
  });
});

See https://css-tricks.com/almanac/properties/t/transition for more details.

PS. Note that your CSS code contains a typo. It should be transparent (without the poundsign, spelt with an 'e').

Eka
  • 28
  • 5