-1

I have an off canvas menu that slides in from the right and sits on top of the page. To prevent a scroll bar I am setting the content section's position to fixed while the menu is open. Problem is, when I close the menu the scroll position on the page is lost, the user is returned to the top of the page.

I am trying to store the scroll position of the page and then set the scroll when the window is closed, but its not working. If I debug the code I can see the scrollTop() functioning as expected, but then it goes into the jQuery.js script and after several function calls it resets the scroll to the top of the page.

What am I doing wrong?

    var scrollPos;

    function openMenu() {
        $('body').addClass('open');
    }

    function closeMenu(compat) {
        $('body').removeClass('open');
    }

    /***  Event Handlers ***/
    $('#js-menu-toggle').on('click', function() {
        scrollPos = $(window).scrollTop();
        openMenu();
    });

    $('#js-menu-close').on('click', function() {
        closeMenu(); 
        $(window).scrollTop(scrollPos);
    });
xpy
  • 5,481
  • 3
  • 29
  • 48
Mikey
  • 366
  • 1
  • 4
  • 20
  • 2
    Maybe all your code is inside a function and when you re-call it `var scrollPos` is reinitialise. However, with this example we can't help you. You need to provide a Minimal, Complete and Verifiable Example (MCVE). See more and then edit your question with a correct working example: http://stackoverflow.com/help/mcve || http://stackoverflow.com/help/how-to-ask – Marcos Pérez Gude Feb 26 '16 at 12:31
  • Store the value in local storage or something and then fetch it from there and scroll to that position. Right now your code re initializing the `scrollPos` variable. – Sudhansu Choudhary Feb 26 '16 at 12:41
  • This is inside my jQuery document.ready function, when I set a breakpoint on the scrollTop(scrollPos); line I can see the correct value is there and if I step into the next line the function works as expected. – Mikey Feb 26 '16 at 12:46
  • The problem is after this works something gets fired in jQuery that resets the scroll of the window to the top of the page – Mikey Feb 26 '16 at 12:47
  • Just a suggestion. Try using a `setTimeout` with 0 seconds delay for settinf the scrollTop to window. http://stackoverflow.com/questions/779379/why-is-settimeoutfn-0-sometimes-useful – Kishor Feb 26 '16 at 14:03

1 Answers1

1

My apologies for not providing enough of an MCVE.

It turns out the problem was the events were bound to an <a> link with a "#" href, so adding in

return false; 

as the last line of the .on events solved my problem.

Mr Lister
  • 45,515
  • 15
  • 108
  • 150
Mikey
  • 366
  • 1
  • 4
  • 20