want to hide/show navbar when scroll down/up using js or jquery

蹲街弑〆低调 提交于 2021-02-19 03:22:08

问题


I simply want to hide navbar when scroll down and show when scroll up so i am adding what i have done but i am unable to acheive it, thanks in advance :)

my html code for navbar

<div class="nav-scroll">
    <nav class="navbar navbar-default navbar-fixed-top">
        <div class="container-fluid">
          <div class="navbar-header">
            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">
              <span class="icon-bar"></span>
              <span class="icon-bar"></span>
              <span class="icon-bar"></span>                        
            </button>
             <img src="/cmm/images/codemymobile-logo-light.svg">
          </div>
          <div class="collapse navbar-collapse" id="myNavbar">
            <ul class="nav navbar-nav navbar-right">
              <li><a href="#myPage">PORTFOLIO</a></li>
              <li><a href="#band">OUR EXPERTISE</a></li>
              <li><a href="#tour">PROCESS</a></li>
              <li><a href="#contact">SERVICE</a></li>
              <li><a href="#contact">CASE STUDIES</a></li>
              <li class="qoute-btn"><a href="#contact">GET A QUOTE</a></li>


            </ul>
          </div>
        </div>
      </nav>
    </div>

my js is as follows

var prevScrollpos = window.pageYOffset;
window.onscroll = function() {
var currentScrollPos = window.pageYOffset;
  if (prevScrollpos > currentScrollPos) {
    document.getElementById("nav-scroll").style.top = "0";
  } else {
    document.getElementById("nav-scroll").style.top = "-50px";
  }
  prevScrollpos = currentScrollPos;
}

回答1:


The first issue in your solution is that you have a class (<div class="nav-scroll">), but you are using document.getElementById(). You should use an id in your HTML () or use document.getElementsByClassName()[0] in your JavaScript.

Your question is flagged with jquery, but your code uses pure JavaScript. Below you can see a version of your code with minor changes to help you to make progress:

window.onscroll = function() {
  var currentScrollPos = window.pageYOffset;

  // 20 is an arbitrary number here, just to make you think if you need the prevScrollpos variable:
  if (currentScrollPos > 20) {
    // I am using 'display' instead of 'top':
    document.getElementById("nav-scroll").style.display = "none";
  } else {
    document.getElementById("nav-scroll").style.display = "initial";
  }
}

After playing a bit with your own solution, you could try to move to jQuery. Here is a link that can be helpful:

https://codepen.io/JTParrett/pen/fnCKE




回答2:


Here's a suggestion:

var lastScrollTop = 0;
$(window).scroll(function(){
  var st = $(this).scrollTop();
  var banner = $('.banner');
  setTimeout(function(){
    if (st > lastScrollTop){
      banner.addClass('hide');
    } else {
      banner.removeClass('hide');
    }
    lastScrollTop = st;
  }, 100);
});

https://codepen.io/marcelo2605/pen/BXQVOO




回答3:


check out this:

document.getElementById("navbar").style.top = "-50px";

In the above line -50px indicates the height of the nav bar if you want to hide the navbar then you have do -50px. If you you navbar height is 90 then use -90.

And one important thing is that your nav must contain id as navbar(i.e id="navbar") Because in javascript you are accessing that id and reducing -50px;

var prevScrollpos = window.pageYOffset;
window.onscroll = function() {
var currentScrollPos = window.pageYOffset;
  if (prevScrollpos > currentScrollPos) {
    document.getElementById("navbar").style.top = "0";
  } else {
    document.getElementById("navbar").style.top = "-50px";
  }
  prevScrollpos = currentScrollPos;
}
body {
  margin: 0;
  background-color: #f1f1f1;
  font-family: Arial, Helvetica, sans-serif;
}

#navbar {
  background-color: #333;
  position: fixed;
  top: 0;
  width: 100%;
  display: block;
  transition: top 0.3s;
}

#navbar a {
  float: left;
  display: block;
  color: #f2f2f2;
  text-align: center;
  padding: 15px;
  text-decoration: none;
  font-size: 17px;
}

#navbar a:hover {
  background-color: #ddd;
  color: black;
}
<div id="navbar">
  <a href="#home">Home</a>
  <a href="#news">News</a>
  <a href="#contact">Contact</a>
</div>

<div style="padding:15px 15px 2500px;font-size:30px;margin-top:30px;">
  <p><b>This example demonstrates how to hide a navbar when the user starts to scroll the page.</b></p>
  <p>Scroll down this frame to see the effect!</p>

</div>



回答4:


I would recommend using CSS to handle the animation as CSS design for it and has, therefore, better performance

Start by adding an event listener to the scroll event of the browser, and then use Document method querySelector to find the navigation bar with a CSS selector, then use the classList property to add or remove a class from the element.

window.addEventListener('scroll', () => {
  if (window.scrollY > 50) {
      return document.querySelector('.navbar').classList.add('hide')
  }
  return document.querySelector('.navbar').classList.remove('hide')

});

You could even simplify it further by using a conditional (ternary) operator to handle the class changes, but it could feel less readable to some.

window.addEventListener('scroll', () => {
   const navbar = document.querySelector('.header-main')      

   navbar.classList[window.scrollY > 50 ? 'add' : 'remove']('hide')

});

Then you could add transition property to animation via CSS for when you want to hide the navbar.

.navbar {
 position: fixed;
 top: 0;
 transition: top 0.5s ease-in-out;
}

.navbar.hide {
   top: -50px
}



回答5:


You can use this approach:

window.addEventListener('scroll', callback);

window.addEventListener('scroll', handleScroll);
let prevScrollPos = window.pageYOffset;
const handleScroll = () => {
  if (process.browser) {
    const currentScrollPos = window.pageYOffset;
    const visible = prevScrollPos > currentScrollPos;
    prevScrollPos = currentScrollPos;
    // here add a class to your navbar
  }
}

For hiding navbar you can add this class to it.

.navbar {
  // actual navbar that has "navbar" class.
  transition: all .3s; // with this navbar will hide with smooth animation.
}
.navbar-hidden {
  top: -200px !important;
}

note: if you are using react, keep on reading:

In where you are adding event listener, do this instead:

useEffect(() => {
  window.addEventListener('scroll', handleScroll);
  return () => {
    window.removeEventListener('scroll', handleScroll);
  };
}, []);

and your callback should look like this:

const [navVisible, setNavVisible] = useState(true);
let prevScrollPos = window.pageYOffset;
const handleScroll = () => {
  const currentScrollPos = window.pageYOffset;
  const visible = prevScrollPos > currentScrollPos;
  prevScrollPos = currentScrollPos;
  if (navVisible !== visible) setNavVisible(visible);
};

And in your jsx code, toggle .navbar-hidden class based on the value of navVisible state.



来源:https://stackoverflow.com/questions/57235230/want-to-hide-show-navbar-when-scroll-down-up-using-js-or-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!