MuaathAli
MuaathAli

Reputation: 117

Moving navigation bar to the top while scrolling down in HTML

I'm trying to make the navigation bar stick to the top when scrolling down. It's easy when the navbar is on top, but since I placed a Div above it I can't seem to figure it out. I tried position fixed and others didnt work. for example like this website www.screencult.com. And btw I'm using Bootstarp.

Here's what I have so far This is what I have

<div id="nav" class="navbar navbar-default navbar-fixed">
            <div class="container">
                <div class="collapse navbar-collapse navHeaderCollapse">
                    <ul class="nav navbar-nav navbar-right">
                        <li><a href="#description" id="color" >ABOUT US</a></li>
                        <li><a id="color" href="#" >GALLERY</a></li>
                        <li><a id="color" href="#contactus" >CONTACT US</a></li>
                    </ul>
                </div>
            </div>
        </div> 

#nav {
    background-color: white;
    border: none;
    border-style: none;
}
#color {
    color: #b5be35; 
    cursor: pointer;
    transition: color 0.5s ease;
}
#color:hover {
    color: #a1a5a2;
}

Upvotes: 0

Views: 2269

Answers (1)

powerc9000
powerc9000

Reputation: 2103

You need to change to position fixed after you have scrolled to a certain point on the page. eg the height of the image.

We use a scroll even listener and scroll top to find out how far we have scrolled

window.addEventListener("scroll", function(e){
      var scrollTop = (window.pageYOffset !== undefined) ? window.pageYOffset : (document.documentElement || document.body.parentNode || document.body).scrollTop;
      //If we have scrolled far enough on the page to be past the image
      //Change the nav to have fixed positioning
      var imageHeight = document.getElementById("image-header").clientHeight
      var nav = document.getElementById("nav");
      if(scrollTop > imageHeight){
          nav.classList.add("fixed-nav");
      }
      else{
          nav.classList.remove("fixed-nav");
      }

});

Upvotes: 2

Related Questions