generatepress icon indicating copy to clipboard operation
generatepress copied to clipboard

Refactor sticky menu and back to top with plain JS

Open thisbit opened this issue 3 years ago • 2 comments

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 avatar Jul 24 '22 19:07 thisbit

@thisbit yes we have plans to remove jQuery completely. Keeping this issue open for future reference. Thanks

JeanPaiva avatar Jul 25 '22 13:07 JeanPaiva

Any news about this? Ran into this again and I just don't want jQuery loaded just for the sticky nav :)

jdevalk avatar Dec 12 '22 10:12 jdevalk