There is the following code.

if ($(window).scrollTop(0)) { $('#console').css('background','blue'); } else { $(window).on('scroll',function(){ $('#console').css('background','red'); }); } 

When scrolling, the background should change, but when the scroll returns to the very top, the background should return.

He unfortunately is not working. How can I make a style change when scrolling? http://jsfiddle.net/FhRKU/39/

    1 answer 1

    1. You need to check .scrollTop() like this: if ($(window).scrollTop() == 0) ;
    2. $(window).on('scroll') needs to be called out of condition. Now you get that if the visitor's scrolling is at the very top, then the handler is not declared.
    3. It is better to take out the entire check and change of styles in a separate function and call it both when the page is loaded and when the page is scrolled.

     function consoleBG() { if ($(window).scrollTop() == 0) { $('#console').css('background', 'blue'); } else { $('#console').css('background', 'red'); } } consoleBG(); $(window).scroll(function() { consoleBG(); }); 
     #console { width: 100%; position: fixed; height: 20px; padding: 3px; } 
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <div id="console"></div> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br>dfsdsd <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br>trhrth <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br>rfwerfwe 

    • Thank! I didn't think about calling the function for some reason ... - Clark