简体   繁体   中英

how to fix a menu on scroll down

Im modifiying a menu on my website here moroccoside.com and im trying to fix the menu once it reaches it with jquery

im using this jquery code on the header but it doesn't function

   <script>
   var stickyOffset = $('.header-wrapper').offset().top;

   $(window).scroll(function(){
   var sticky = $('.header-wrapper'),
   scroll = $(window).scrollTop();

   if (scroll >= stickyOffset) sticky.addClass('fixed');
   else sticky.removeClass('fixed');
   });
   </script> 

here is the fixed css class

   .fixed {position:fixed; z-index: 9999;}

notice: i put the script in the header not from external js file

any help will be so appretiated

You forgot to wrapped in document.ready function. Try this:

jQuery(document).ready(function($){
  var stickyOffset = $('.header-wrapper').offset().top;

   $(window).scroll(function(){
     var sticky = $('.header-wrapper'),
     scroll = $(window).scrollTop();

     if (scroll >= stickyOffset) sticky.addClass('fixed');
     else sticky.removeClass('fixed');
   });
});

You need to be sure the DOM has loaded before this runs. Try this:

$(document).ready(function(){
  var stickyOffset = $('.header-wrapper').offset().top;

   $(window).scroll(function(){
   var sticky = $('.header-wrapper'),
   scroll = $(window).scrollTop();

   if (scroll >= stickyOffset) sticky.addClass('fixed');
   else sticky.removeClass('fixed');
   });
)};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM