cecileRx
cecileRx

Reputation: 135

Hide the upper part of the navbar when scroll (smoothly!)

Hello I customized a Bootstrap navbar with 2 rows (the upper part is just logo and social links and the down part are navigation links). I am trying to hide the upper part when scrolling but I can't find a way to do it smoothly. I think the code below is the best solution I found, but for now the eventlistener on transitionend doesn't work and the class 'hidden' is never added.

var scrollpos = window.scrollY;
var header = document.getElementById("header-up-section");

function add_class_on_scroll() {
    header.classList.add('visuallyhidden');
    header.addEventListener('transitionend', function(e) {
      header.classList.add('hidden');
    }, {
      capture: false,
      once: true,
      passive: false
    });
}

function remove_class_on_scroll() {
     header.classList.remove('hidden');
    setTimeout(function () {
      header.classList.remove('visuallyhidden');
    }, 20);
}

window.addEventListener('scroll', function(){

    scrollpos = window.scrollY;

    if(scrollpos > 20){
        add_class_on_scroll();
    }
    else {
        remove_class_on_scroll();
    }
    console.log(scrollpos);
});

*/and CSS :

#header-up-section.visuallyhidden {
  opacity: 0;
}

#header-up-section.hidden {
  display: none !important;
}

The header-up-section turns invisible but the div is not hidden. Any idea to help?

Upvotes: 1

Views: 840

Answers (1)

cecileRx
cecileRx

Reputation: 135

Finally no need for JS to do this. Just need 2 bootstrap navbars and add to the second one (which is a pseudo 'down part' of a two rows navbar) the bootstrap class 'sticky-top'. It does the job perfectly ;)

Upvotes: 0

Related Questions