Reputation: 759
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
Upvotes: 3
Views: 1739
Reputation: 10414
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
});
Upvotes: 4
Reputation: 66228
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 (i.e. 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 :)
Upvotes: 3