AAlleavitch
AAlleavitch

Reputation: 121

Saving scroll position while using position: fixed to prevent body scrolling on iphone

What I'm trying to do is have it so that the body is no longer scroll-able while the mobile menu is open, but the position on the page is saved so that when the body's position becomes fixed and unfixed again the user doesn't lose their place on the page.

The below works perfectly when I try it in Chrome dev-tool's emulator for the iphone, but it does not work on my actual iphone SE (on both Chrome and Safari). Does anyone have any insight as to why this is the case?

function storeBodyScroll() {
    var scrollpos = $('html').scrollTop();
    $('body').css({top: -scrollpos});
}

function closeMenu() {
    // See if the body's scroll position is being held
    var scrollpos = parseInt($('body').css('top'), 10);

    $('body').removeClass('mobile-menu-open');

    // Scroll to it if it is and remove held position
    if (!!scrollpos && scrollpos < 0) {
        $('html').scrollTop(-scrollpos);
        $('body').css({top:0});
    }
}

function openMenu() {
    storeBodyScroll();
    $('body').addClass('mobile-menu-open');
}
body.mobile-menu-open {
    position: fixed;
    overflow-y: scroll;
}

Upvotes: 3

Views: 1294

Answers (1)

AAlleavitch
AAlleavitch

Reputation: 121

Making this work the way I intended on the iphone actually ended up being a simple fix: it seems that $('html').scrollTop() doesn't return the value I was expecting.

Instead, I replaced $('html').scrollTop() with $(window).scrollTop(), and replaced $('html').scrollTop(-scrollpos) with window.scrollTo(0,scrollpos).

Upvotes: 1

Related Questions