The problems run deeper than just "smaller mobile", given that anything that takes down more height -- even at 4k -- can be an annoyance or usability issue for users.

Though there is an easy answer if the part being held in place isn't too obtrusive. Media query the "fixed" so it remains static, which would ignore all the positioning.

That said, you've flipped the bird at accessibility by way of using pixel metrics, you have no handling of wrapping since you used a fixed 70px instead of extracting nav.innerHeight... and of course the elephant in the room...

The steaming pile of mentally enfeebled incompetent TRASH that is jQuery. (but let me tell you what I really think of jQ)

Likewise the waste of jQ's idiotic "ready" on something you could/should assign without an event, your scroll event should also be hooked by resize, jQ's derpy $(selector) crap making the events take longer to run which is something you should try to avoid in events, etc, etc, etc.

If we were to set the nav to:

nav {
top:0;
left:0;
width:100%;
background: #fff;
text-align:center;
}

all the script would need to do is add nav.style.position = ‘fixed’; when we want it sticky, and ‘static’ when we don’t. Remember, static ignores top/left/bottom/right.

(function(d, w) {  var nav = d.querySelector('nav');  w.addEventListener('scroll', scrollHandler, false);
w.addEventListener('resize', scrollHandler, false);
d.addEventListener('load', scrollHandler, false);

function scrollHandler() {
nav.style.position = (
(w.scrollY || w.pageYOffset) >
(w.innerHeight - nav.offsetHeight)
) ? 'fixed' : 'static';
}

})(document, window);

Boom, better functionality since we are no longer dependent on a hard-coded height! Also executes faster reducing that pesky scroll/resize overhead, and tests for it when the page is rendered since hash-links on page could have us already scrolled down!

Remember that, any scroll effect should also test when document.onload and window.resize fire, as those too can change the scroll position!

Also does an excellent job of showing how 100% stupid jQuery is, since where exactly did jQ save you ANY effort? If we discount the added listeners, the above doesn’t only run faster, it’s less code! Even with the IIFE for scope isolation and the storage of NAV so we aren’t going full Gungan grabbing the element via selector every blasted time.

Meesa says yewz nevah goes full Gungan…

Pen here:

Written by

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store