Hello everybody.
I’m actually finishing the 2nd project, the portfolio. So i have a navbar with anchors in it that takes me to different ids. The classes just covered the basics of jquerry and since i’m not yet good enough with javascript i found this script online in order to have a smooth scrolling and for my anchors to turn active when clicked. Here is the script
$(document).ready(function () {
$(document).on("scroll", onScroll);
//smoothscroll
$('a[href^="#"]').on('click', function (e) {
e.preventDefault();
$(document).off("scroll");
$('a').each(function () {
$(this).removeClass('active');
})
$(this).addClass('active');
var target = this.hash,
menu = target;
$target = $(target);
$('html, body').stop().animate({
'scrollTop': $target.offset().top+2
}, 500, 'swing', function () {
window.location.hash = target;
$(document).on("scroll", onScroll);
});
});
});
function onScroll(event){
var scrollPos = $(document).scrollTop();
$('#menu-center a').each(function () {
var currLink = $(this);
var refElement = $(currLink.attr("href"));
if (refElement.position().top <= scrollPos && refElement.position().top + refElement.height() > scrollPos) {
$('#menu-center ul li a').removeClass("active");
currLink.addClass("active");
}
else{
currLink.removeClass("active");
}
});
}
So it works fine, it takes me the the # and turns active but the link i clicked will stay active no matter where i scroll after. If i click on contact it will take me to #contact and in the navbar contact will turn active but if i scroll back up to infos contact will still be active and not infos. I would like for my a elements to activate/deactivate if i scroll over them.
Any idea how i can do that ?
Thanks !
Edit : Here is my project https://codepen.io/Altho/pen/Gybdbm