Need help with jquerry and nov objects

Need help with jquerry and nov objects
0

#1

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


#2

Which part of the JavaScript did you write vs copied/pasted? I ask because you seem to be referencing html elements which do not exist in your html. For example:

$('#menu-center a').each(function () {

I do not see an element with id=“menu-center” in your html, yet you are trying to select all the anchors in this element and iterate over them.

To make the code work as you are want, all I did was make a change to the above line of code. I made a reference to the correct set of anchors which actually exist in your code. I will leave it to you to figure that part out.


#3

It works ! thanks ! I knew how jquerry selectors worked yet for some reason i completely didnt pay attention to that

 $('.navbar-nav a').each(function () {

thanks again