I'm having problems integrating a navigation bar that highlights the current section being viewed on the website. I just want the currently viewed section to be 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>
I added two line of code, one to remove bold from all href in navigation, and one to add bold to href that is clicked. Take a look at 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);
}
});
}
I tried to solve this by using the jQuery's offset().top and checking it against the window's scrollTop.
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); } });
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.