Home > Net >  Script for hiding navbar...not on top, neither on bottom of scroll
Script for hiding navbar...not on top, neither on bottom of scroll

Time:04-15

Im a graphic designer with a little knowledge of code... but this is driving me nuts...

I got a classic navigation bar thats hidden unless user scrolls a little bit down. I got this action with javascript. OK.

But I want this happens (the action of showing navigation bar) only on the middle of every page. Like 100px away from top and 100px away from bottom of the scroll. The reason is I got breadcrumbs on top and footer on bottom of the page, I dont need the navbar there.

I tried my best to mix what I got (the navbar) with some scroll detectors, or reading bars that get scroll position... but was impossible to get something work...

¿any help please?

My code is this right now, only the navbar (improvements welcome too...heheh):

    var prevScrollpos = window.pageYOffset;
window.onscroll = function() {
  var currentScrollPos = window.pageYOffset;
  if (prevScrollpos > currentScrollPos) {
    document.getElementById("navbar").style.bottom = "0";
  } else {
    document.getElementById("navbar").style.bottom = "-100px";
  }
  prevScrollpos = currentScrollPos;
}

CodePudding user response:

If I understood you correctly, I believe you want something like this:

    window.onscroll = () => { 
        const scrollPos = window.scrollY; 
        const offset = 100; const targetEl = document.body; //Adjust to preference 
        if(scrollPos > offset && (targetEl.scrollHeight - window.innerHeight - scrollY) > offset )
            console.log('shownavbar')
        else
            console.log('hidenavbar')
    }

CodePudding user response:

Got it thanks to @NourAshraf. I did some changes with the code I got before and yours. Now works perfect!

Just if anyone need it finally is something like this. To check it easier I put to change the body colour to green (when the navigation bar should show) and red (when should not appear).

var prevScrollpos = window.pageYOffset;
window.onscroll = function() {
  var currentScrollPos = window.pageYOffset;
  var offset = 500; const targetEl = document.body; //Adjust to preference 

  if (prevScrollpos > currentScrollPos && currentScrollPos > offset && (targetEl.scrollHeight - window.innerHeight - scrollY) > offset) {
    document.body.style.backgroundColor = "green";
  } else {
    document.body.style.backgroundColor = "red";
  }
  prevScrollpos = currentScrollPos;
}
  • Related