1

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.

wondering
  • 56
  • 10
  • 1
    Why not just use CSS for this? Like `#grey.active { styles }` or `#grey1.active { styles }`? Or is there some larger issue you are trying to solve? – disinfor Jan 02 '23 at 23:05
  • @disinfor Thanks, this works perfectly. I also managed to find a solution using jquery and css, I'm wondering which one of these is best practice. I added classes to all my anchors through jquery and then styled them with css using the new class so they changed when active, following is my code: 'if ($(".anchor1").hasClass("active")) { $(".anchor1").addClass("anchor1active"); } else { $('.anchor1').removeClass('anchor1active'); }' css: '.anchor1active { styles } – wondering Jan 04 '23 at 19:40
  • In my opinion, using JS/jQuery for this is overkill. There isn't a best practice really (since it depends on use case), but if it was me, I wouldn't add/remove classes if the issue can be solved by CSS only. – disinfor Jan 04 '23 at 20:28

0 Answers0