JSON_Derulo
JSON_Derulo

Reputation: 992

How to set scroll position with jQuery?

I found a solution to a similar problem I am having HERE. However I can't get it to work for myself. The problem I encountered was when trying to lock vertical scroll while the mobile menu was opened on a site I am working on. Locking the scroll caused the page to jump to the top each time the menu was opened.

jQuery:

timber.openDrawerMenu = function () {
    var tempScrollTop = $(window).scrollTop();
    var $mobileMenu = $('.nav-bar'),
    $mobileMenuButton = $('#menu-opener'),
    $body = $('body');
    $mobileMenuButton.addClass('opened');
    $mobileMenu.addClass('opened');
    $body.addClass('opened-drawer');

  // Make drawer a11y accessible
  timber.cache.$navBar.attr('aria-hidden', 'false');

  // Set focus on drawer
  timber.trapFocus({
     $container: timber.cache.$navBar,
     namespace: 'drawer_focus'
  });

  // Escape key closes menu
  timber.cache.$html.on('keyup.drawerMenu', function(evt) {
    if (evt.keyCode == 27) {
      timber.closeDrawerMenu();
    }
  });
  console.log(tempScrollTop);
  $(window).scrollTop(tempScrollTop);
}

I added the console.log() statement in order to see if the script was caputuring the proper scrollTop value and in fact it is. For some reason it is not setting the scroll position though and I am not able to figure out why exactly. Any help here is greatly appreciated.

Upvotes: 2

Views: 2506

Answers (1)

K.F
K.F

Reputation: 469

I see that this is a mobile specific problem.

  1. I have 1 thought on that:
    • Try explicitly setting position: relative on the body tag.
  2. If that doesn't work, I have a more hacky thought:
    • Try explicitly resetting the scroll location just before closing the menu.

Hope those work, if not, leave a comment :)

Upvotes: 1

Related Questions