zeshanshani
7/30/2017 - 5:53 PM

Fixed navbar on scroll by checking the current navbar position and applying the class only when the navbar.offset().top is larger than $wind

Fixed navbar on scroll by checking the current navbar position and applying the class only when the navbar.offset().top is larger than $window.scrollTop

/**
 * Fix Navbar on Scroll
 *
 * replace {.header-area} width your header CSS class selector 
 * replace {header-area-fixed} with your CSS class for fixed header
 */
jQuery(document).ready(function($) {

  var $body = $('body'),
      $window  = $(window);

  $window.ready(fixNavbarOnScroll).resize(function() {
    fixNavbarOnScroll();
  });

  function fixNavbarOnScroll( width ) {
    var $navbar      = $('.header-area'),
        $wpadminbar  = $('#wpadminbar'),
        navbarTop, $navbarWrapper;

    if ( ! $navbar.parent('.header-area-wrapper').length ) {
      $navbar.wrapAll('<div class="header-area-wrapper"></div>');
    }

    $navbarWrapper = $navbar.closest('.header-area-wrapper');
    
    navbarTop = $navbarWrapper.offset().top - $wpadminbar.outerHeight();

    $navbarWrapper.css({
      minHeight: $navbar.outerHeight()
    });

    $window.scroll(function() {

      if ( $(this).scrollTop() >= navbarTop ) {
        $navbar.addClass( 'header-area-fixed' );
      } else {
        $navbar.removeClass( 'header-area-fixed' );
      }

    });
  }

});
.header-area.header-area-fixed
{
    position: fixed;
    width: 100%;
    left: 0;
    top: 0;
}

.admin-bar .header-area.header-area-fixed
{
    top: 32px;
}