generatepress
generatepress copied to clipboard
Refactor sticky menu and back to top with plain JS
Description
GeneratePress managed to almost completely get rid of jQuery. It remains, as far as I understand in Sticky TopBar feature and back to top button. Both of which are super simple to code without jQuery.
I have been using this for a while now and it changes toggles classes down and up on the body element when someone scrolls up or down. Having this happen on the body one can use the same script to sticky and unsticky any element on the page, or any number of elements on the page, by simply saying something like:
.down .site-header {display: none;} .site .site-header {display: block;} .site-footer {display: none;} .site-footer {display: none;}
Or any other css way of handling hiding and showing.
/**
* A better scroll watcher
*/
window.addEventListener( 'DOMContentLoaded', ()=> {
const body = document.body,
scrollUp = "up",
scrollDown = "down",
offset = 0;
let lastScroll = window.pageYOffset;
if ( lastScroll > offset ) {
body.classList.add(scrollUp);
}
window.addEventListener('scroll', ()=> {
const currentScroll = window.pageYOffset;
if ( currentScroll <= offset ) {
body.classList.remove(scrollUp);
return;
}
if ( currentScroll > lastScroll && !body.classList.contains(scrollDown) ) {
body.classList.remove(scrollUp);
body.classList.add(scrollDown);
} else if ( currentScroll < lastScroll && !body.classList.contains(scrollUp) ) {
body.classList.remove(scrollDown);
body.classList.add(scrollUp);
}
lastScroll = currentScroll;
})
});
References
For example topbar here uses it.
https://stage.apuri.hr/
Hopefully this might be useful.
@thisbit yes we have plans to remove jQuery completely. Keeping this issue open for future reference. Thanks
Any news about this? Ran into this again and I just don't want jQuery loaded just for the sticky nav :)