Search code examples
javascripthtmljquerybootstrap-4

how can i toggle site header in javascript or jquery


I have designed a menu using Bootstrap. I want the menu to be hidden when I scroll down, and the menu to be displayed if I scroll up. (slide-down / slide-up).

I want to use jQuery for this functionality.

window.onscroll = function() {
  scrollFunction()
};

function scrollFunction() {
  if (document.body.scrollTop > 150 || document.documentElement.scrollTop > 150) {

    $('.center-menu').slideUp();

    $(bottomDiv).fadeIn();
  } else {
    $('.center-menu').slideDown();
    $(bottomDiv).fadeOut();
  }
}

Solution

  • This use case can be performed using JQuery. You can hide a div using a call like this:

     $('#menu').hide();
    

    To show a div, use this call:

    $('#menu').show()
    

    Of course, you need to put in logic to handle the scroll. Something like this will work.

    var lastScrollTop=150;
    $(window).scroll(function(event){
       var st = $(this).scrollTop();
       if (st > lastScrollTop){
           // downscroll code
       } else {
          // upscroll code
       }
       lastScrollTop = st;
    });
    

    More information here.