Single Page Website - Navigation: Highlight the current section

I am having problems merging a navbar that highlights the current section being viewed on a website. I just want the section I am viewing in bold in the navigation bar.

Here is the codepen :

Html

  <nav id="nav-wrap">
    <ul>
      <li class="current"><a class="page" href="#home">Home</a></li>
      <li><a class="page" href="#about">About</a></li>
      <li><a class="page" href="#portfolio">Portfolio</a></li>
      <li><a class="page" href="#scrapbook">Scrapbook</a></li>
      <li><a class="page" href="#contact">Contact</a></li>
    </ul>
  </nav>

  <div class="header-content">
    <img id="logo" src="img/logo.png" alt="logo" height="200px" width="200px">
    <h3>Joseph Cooper</h3>
    <h3>Graphic Designer</h3>
    <p> 10.03.97 </p>
  </div>

<a href="#about"><img id ="down" src="img/down.png" height="42px" width="42px"></a>

      

+3


source to share


2 answers


I added two lines of code, one to remove the bold font from all hrefs in the navigation, and one to add the bold font to the href that is clicked. Take a look at the codepen: http://codepen.io/anon/pen/doaRjy



   function smoothScroll (duration) {
      $('a[href^="#"]').on('click', function(event) {        
          var target = $( $(this).attr('href') );

          $("#nav-wrap a").css('font-weight','normal')/*this line remove bold from all href*/
          $(this).css('font-weight','bold')/*this line add bold to clicked href*/

          if( target.length ) {
              event.preventDefault();
              $('html, body').animate({
                  scrollTop: target.offset().top
              }, duration);
          }
      });
    }

      

+1


source


I tried to solve this problem using jQuery offset (). top and checking it against the scrollTop window.



var $window = $(window),
  homeLink = $("a[href='#home']"),
  aboutLink = $("a[href='#about']"),
  portfolioLink = $("a[href='#portfolio']");

$window.on("scroll", function(e) {

  if ($window.scrollTop() < $("#about").offset().top) {

    $("#nav-wrap").find("a").css("font-weight", 400);
    homeLink.css("font-weight", 900);

  } else if ($window.scrollTop() > $("#about").offset().top && $window.scrollTop() < $("#portfolio").offset().top) {

    $("#nav-wrap").find("a").css("font-weight", 400);
    aboutLink.css("font-weight", 900);

  }

});
      

Run codeHide result


0


source







All Articles