How to change color while scrolling user

I have a piece of jQuery code that changes the elements of a pair of colors when users scroll down. But when the user scrolls back the page, I want to switch to the original color. This does not work as I expect ...

Source 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 an additional CSS modifier for the first if the 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" });
})
+4
source share
1 answer

I see that you are missing the parentheses in ifand else. Therefore, only the first line following ifand is executed else. Instead, add a figure like this:

 .....
 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" });
 }
 ....
+3

Source: https://habr.com/ru/post/1611708/


All Articles