Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Mobile: Make the header hide on scroll down and show on scroll up

A common thing we see in many mobile apps is when the user scrolls down the page the header disappears and when they scroll up the page the header appears. How do we achieve this in jQuery Mobile? (I'm answering my own question below)

like image 345
Sean Bannister Avatar asked Jan 21 '14 04:01

Sean Bannister


1 Answers

/**
 * Header scroll control
 * When the user scrolls down the page hide the header, when they scroll up show it.
 */
var lastScrollPosition;

$(document).scroll( function() {
  var scrollPosition = $(this).scrollTop();

  // Scrolling down
  if (scrollPosition > lastScrollPosition){
    // If the header is currently showing
    if (!$('[data-role=header].ui-fixed-hidden').length) {
      $('[data-role=header]').toolbar('hide');
    }
  } 

  // Scrolling up
  else {
    // If the header is currently hidden
    if ($('[data-role=header].ui-fixed-hidden').length) {
      $('[data-role=header]').toolbar('show');
    }
  }

  lastScrollPosition = scrollPosition;  
});
like image 99
Sean Bannister Avatar answered Sep 29 '22 08:09

Sean Bannister