steve0nz
steve0nz

Reputation: 906

How to change color when user scrolls

I have a piece of jQuery code which changes the elements of a couple of colors when the users scrolls down. But when the user scrolls back up the page, I want to switch to the original color. It doesn't work the way I expect...

Original Code that works

jQuery(window).scroll(function() 
{
    var scrollTop = jQuery(this).scrollTop(),
    offset = jQuery('#masthead').height() - 55;
    if ( scrollTop < offset ) 
        jQuery(".float-manu").css({ backgroundColor: "rgba(0,0,0,0)" });
    else 
        jQuery(".float-manu").css({ backgroundColor: "rgba(0,0,0,0.7)" });
})

Modified code that also works

})(window.jQuery);
jQuery(window).scroll(function() 
{
    var scrollTop = jQuery(this).scrollTop(),
    offset = jQuery('#masthead').height() - 55;
    if ( scrollTop < offset ) 
        jQuery(".float-manu").css({ backgroundColor: "rgba(0,0,0,0)" });
    else 
        jQuery(".float-manu").css({ backgroundColor: "rgba(0,0,0,0.7)" });
        jQuery(".primary-menu a").css({ color: "white" });
})

Adding in additional css modifier to first if statement kills the script.

})(window.jQuery);

jQuery(window).scroll(function() 
{
    var scrollTop = jQuery(this).scrollTop(),
    offset = jQuery('#masthead').height() - 55;
    if ( scrollTop < offset ) 
        jQuery(".float-manu").css({ backgroundColor: "rgba(0,0,0,0)" });
        jQuery(".primary-menu a").css({ color: "black" });
    else 
        jQuery(".float-manu").css({ backgroundColor: "rgba(0,0,0,0.7)" });
        jQuery(".primary-menu a").css({ color: "white" });
})

Upvotes: 4

Views: 97

Answers (1)

Sandeep Nayak
Sandeep Nayak

Reputation: 4757

I see that you are missing the brace in your if and else. Hence only the first line following the if and else gets executed. Instead add a brace like so:

 .....
 if ( scrollTop < offset ) {
      jQuery(".float-manu").css({ backgroundColor: "rgba(0,0,0,0)" });
      jQuery(".primary-menu a").css({ color: "black" });
 }
else {
     jQuery(".float-manu").css({ backgroundColor: "rgba(0,0,0,0.7)" });
     jQuery(".primary-menu a").css({ color: "white" });
 }
 ....

Upvotes: 3

Related Questions