Mike
Mike

Reputation: 103

navigation bar scroll when clicked

<div class="navbar">
  <nav class="navbar navbar-dark bg-inverse navbar-fixed-top">
       <div class="container-fluid">
    <div class="navbar-header">
      <a class="navbar-brand" href="#">company name</a>
    </div>
    <ul class="nav navbar-nav navbar-right ">
      <li><a href="#" style="color:white;">About</a></li>
      <li><a href="#" style="color:white;">Portfolio</a></li>
      <li><a class="portfolio-scroll" href="#" style="color:white;" id="contact-nav">Contact</a></li>
    </ul>
</div>
</nav>

i wanted to make my navbar when one of the option in the navbar is clicked the page would scroll to that specific section in the page, for example when i click contact on my navbar the page would scroll down to the contact section in the same page

how to make something like that, can anyone help me ?

Upvotes: 4

Views: 29180

Answers (3)

Anand Kishor
Anand Kishor

Reputation: 61

You can use ids for scrolling.

Simply, put the id in like this

   <div id="about"></div> 

then in a href you can do something like this,

   <a href="#about">Click to scroll</a>

Also, for avoiding the sudden pop and for a smooth transition effect you can write the following in css.

   html{
     scroll-behavior: smooth;;
   }

Upvotes: 6

Dave
Dave

Reputation: 2900

You may want to use javascript for that. Here is my example.

$("a").click(function(){
  var pageId = $(this).attr("data-page");
  $("html, body").animate({ scrollTop: $("#"+pageId).offset().top }, 1000);
});
div.page {
  min-height:1000px;
  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<div class="navbar">
  <nav class="navbar navbar-dark bg-inverse navbar-fixed-top">
       <div class="container-fluid">
    <div class="navbar-header">
      <a class="navbar-brand" href="#">company name</a>
    </div>
    <ul class="nav navbar-nav navbar-right ">
      <li><a href="#" style="color:blue;" data-page="about">About</a></li>
      <li><a href="#" style="color:blue;" data-page="portfolio">Portfolio</a></li>
      <li><a class="portfolio-scroll" href="#" style="color:blue;" id="contact-nav" data-page="contact">Contact</a></li>
    </ul>
</div>
    
    <div class="page" id="about"><h1>About</h1></div>
    <div class="page" id="portfolio"><h1>Portfolio</h1></div>
    <div class="page" id="contact"><h1>Contact</h1></div>
</nav>

Upvotes: 3

Perry Mitchell
Perry Mitchell

Reputation: 694

You can do this easily using HTML anchors.

Give your section, say "About", an ID:

<h1 id="about">About</h1>

And then change your anchor's link:

<a href="#about" style="color:white;">About</a>

And when you click the anchor, it will automatically scroll to the correct place. The best thing about this is that it requires no javascript, and is supported in every browser.

Note: You also have your end tags switched around - </div> and </nav> are in the wrong order.

Upvotes: 16

Related Questions