How to add a class when another class is active

157 Views Asked by At

I have an anchor menu and when the anchor link is active it adds a class to that link. I'm trying to add an additional class to each anchor link individually when it's active, so I can make different changes to each one. Following is my anchor menu html:

<div class="anchor-menu" id="background">
      <div><a href="#service1" class="anchor1 nav-link" id="grey"></a></div>
      <div><a href="#service2" class="anchor2 nav-link" id="grey1"></a></div>
      <div><a href="#service3" class="anchor3 nav-link" id="grey2"></a></div>
      <div><a href="#service4" class="anchor4 nav-link" id="grey3"></a></div>
    </div>

Following is the jquery that adds the class 'active' to the active anchor link.

 <script>
    $(document).ready(function () {

      var sectionIds = $('a.nav-link');

      $(document).scroll(function () {
        sectionIds.each(function () {
          var container = $(this).attr('href');
          var containerOffset = $(container).offset().top - 300;
          var containerHeight = $(container).outerHeight();
          var containerBottom = containerOffset + containerHeight;
          var scrollPosition = $(document).scrollTop();

          if (scrollPosition < containerBottom && scrollPosition >= containerOffset) {
            $(this).addClass('active');
          } else {
            $(this).removeClass('active');
          }
        });
      });
    });
  </script>

So basically what I'm trying to do is that when id=grey has the class active added to it it should add an additional class to it. And so on for all the other anchor links. So I should be able to set styling for each element that becomes active seperately.

0

There are 0 best solutions below