简体   繁体   中英

jQuery: toggle header class on scroll and if page is not at top

I have a jQuery snippet which toggles the class tinyHead on the header when the user scrolls the page.

jQuery(document).ready(function($) {
    $(window).on('scroll touchmove', function () {
        $('#header').toggleClass('tinyHead', $(document).scrollTop() > 0);
    });
});

This works with no problems, however, if a user refreshes the page after they have scrolled down then when the page reloads the tinyHead class is not on the header. If they then scroll the class toggles on.

What I need is for the script to check if the page is at the top of the viewport and if it isn't then to add the class tinyHead

Thank you

That's normal, your callback function is never executed if the user doesn't scroll or touchmove or does whatever event you attached your function to.

You have to trigger the attached callback function at least once, you can do it simply by faking a scroll event just after doing the binding:

jQuery(document).ready(function($) {
    $(window).on('scroll touchmove', function () {
        $('#header').toggleClass('tinyHead', $(document).scrollTop() > 0);
    }).scroll();  // << Add this
});

You will have to execute the function on page load (or DOM ready), in addition to calling it during scroll or touchmove events. Instead of repeating the function twice, you can do this:

jQuery(document).ready(function($) {
    var tinyHead = function() {
        $('#header').toggleClass('tinyHead', $(document).scrollTop() > 0);
    }

    // Call tinyHead() when DOM is ready / upon page load
    tinyHead();

    // Call tinyHead() when scroll or touchmove events are registered
    $(window).on('scroll touchmove', tinyHead);
});

p/s: On a side note, you might want to look into throttling your scroll event — some browsers "overfire" the event (ie calling it too frequently). Since tinyHead() is a rather lightweight function, I personally don't think throttling the scroll event will bring about massive performance improvements, but if your tinyHead() function is computationally heavy, you might want to look into this option :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM