Search code examples
javascriptnavbarsticky

sticky navbar does not work on mobile while scrolling


I've created a sticky navbar for a subnav, which should stick at the top of the screen when the user scrolls down. Therefore I've tried some javascript, which changes the position to 'fixed' when the top is reached. Avoiding a gap in the content when the navbar is taken out of the flow, I've also added a placeholder, which has the same height as the navbar.

On Desktop it really works and looks how it should be. But I got a "touch" issue on mobile view. When I scroll down on mobile view the navbar will not appear during the process of scrolling over the viewpoint, where the css class is changing. It only appears when I stop scrolling after that viewpoint. When it shows up I can normally scroll up and down and I am only getting this issue again if I repeat this procedure, where the navbar has to change the css class. So it might be a problem with the css class change and I guess the problem could be in the javascript snippet. Does anybody know a solution for this? I'd like to have the same behavior like on desktop view, so the navbar is always visible and just fixed to the very top of the screen, even if it is in the flow of scrolling.

JS:

var menu = document.querySelector('#irp-localnav');
var menuPosition = menu.getBoundingClientRect();
var placeholder = document.createElement('div');
placeholder.style.width = menuPosition.width + 'px';
placeholder.style.height = menuPosition.height + 'px';
var isAdded = false;

window.addEventListener('scroll', function() {
if (window.pageYOffset >= menuPosition.top && !isAdded) {
    menu.classList.add('sticky');
    menu.parentNode.insertBefore(placeholder, menu);
    isAdded = true;
} else if (window.pageYOffset < menuPosition.top && isAdded) {
    menu.classList.remove('sticky');
    menu.parentNode.removeChild(placeholder);
    isAdded = false;
}
});

If you guess an error in the html/css markup, just let me know, so I get in touch with you again by posting this markup

Kind Regards


Solution

  • I was able to hack around. For anyone, who is facing a similiar issue:

    Mobile browsers simply do not fire on a scroll event, while the event is in process. They fire when the event has stopped, so, when you've stopped scrolling. Using translate3d(0px,0px,0px) can solve this. Refer to this thread to read more about it:

    iOS 9 Safari: changing an element to fixed position while scrolling won't paint until scroll stops

    Kind Regards!