Archived topic
It is possible to use sticky header without jquery?
5 replies · Started by Fabio on December 17, 2020
Hi all i just understood that sticky navigation requires jquery to work, but in my website i disabled jquery and i would like to know if it is possible to use fixed navigation even without usign Jquery, i dont't know, with Vanilla or Css or what esle
thank you
ok i found this:
https://generatepress.com/forums/topic/dont-want-to-use-jquery-and-still-want-sticky-navigation-with-css/
i had to make the css on .site-header and it seems to works, but, is there any ways to emulate the jquery functions like showing the fixed header only when scrolling up?
Hi there,
its not possible to do the transition with CSS alone, it would require some JS to do that. We will be replacing jQuery in the next update with Vanilla JS.
uh uh love you so much ! Vanilla Vanilla :-)
i was just testing this: https://codingreflections.com/hide-header-on-scroll-down/
it works for me adding a padding-top:50px on body element
but i will wait for your news update !!
thank you
temporary solution:
<script>
(function(){
var doc = document.documentElement;
var w = window;
var prevScroll = w.scrollY || doc.scrollTop;
var curScroll;
var direction = 0;
var prevDirection = 0;
var header = document.getElementById('masthead');
var checkScroll = function() {
/*
** Find the direction of scroll
** 0 - initial, 1 - up, 2 - down
*/
curScroll = w.scrollY || doc.scrollTop;
if (curScroll > prevScroll) {
//scrolled up
direction = 2;
}
else if (curScroll < prevScroll) {
//scrolled down
direction = 1;
}
if (direction !== prevDirection) {
toggleHeader(direction, curScroll);
}
prevScroll = curScroll;
};
var toggleHeader = function(direction, curScroll) {
if (direction === 2 && curScroll > 50) {
header.classList.add('hide');
prevDirection = direction;
}
else if (direction === 1) {
header.classList.remove('hide');
prevDirection = direction;
}
};
window.addEventListener('scroll', checkScroll);
})();
</script>
<style>
body{padding-top:50px}
#masthead {
position: fixed;
height: 50px;
top: 0px;
width: 100%;
z-index: 100;
transition: all .3s ease;
}
#masthead.hide {
top: -51px;
}
</style>
You're welcome - and thanks for sharing your solution :)