Search code examples
jquerywordpressscrollscrolltop

Changing colour of header background on scroll


I'm trying to change the background colour of the header for my WordPress site on scroll. I am using the scrollTop function to achieve this but for whatever reason the value is currently being returned as a function. Using the below code to the log the scroll position to the console I am getting this:

ƒ (e){return $(this,function(e,t,n){var r;if(x(e)?r=e:9===e.nodeType&&(r=e.defaultView),void 0===n)return r?r[i]:e[t];r?r.scrollTo(o?r.pageXOffset:n,o?n:r.pageYOffset):e[t]=n},t,e,arguments.length)}

jQuery(document).ready(function($) {
    $(window).scroll(function() {
        console.log($(window).scrollTop());
    });
});

As the scroll position isn't being returned as a value I can't use it to write the logic for my header. From what I've seen scrollTop should initially log to the console 0, then increase as the window scrolls. I was wondering if anyone else had run into the same issue.


Solution

  • I made you an example of setting the title color using the addClass() method when scrolling. When the scrolling position is returned, the class with the desired color is removed - removeClass():

    if ($(window).scrollTop() > 0) {
       $("p").addClass("color_scroll");
    } else {
       $("p").removeClass("color_scroll");
    }
    

    $(document).ready(function() {
      $(window).scroll(function() {
        if ($(window).scrollTop() > 0) {
          $("p").addClass("color_scroll");
        } else {
          $("p").removeClass("color_scroll");
        }
      })
    })
    body {
      height: 5000px;
    }
    
    p {
      position: sticky;
      top: 0;
    }
    
    p.color_scroll {
      color: green;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <p>Title</p>