skip to Main Content

I have a CMS collection where I can’t assign specific IDs to sections. I have the following code working to scroll to each section on click. I’m wondering if there is a cleaner way to condense the jQuery down to a single function? I may have up to 9 instances of this. Is there a way to loop through the eq 0-9?

HTML

<nav>
  <div class="link">Link 1</div>
  <div class="link">Link 2</div>
  <div class="link">Link 3</div>
</nav>

<div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
</div>

jQuery

$(".link")
  .eq(0)
  .on("click", function () {
    $("html, body").animate(
      { scrollTop: $(".item").eq(0).offset().top },
      1000
    );
  });

$(".link")
  .eq(1)
  .on("click", function () {
    $("html, body").animate(
      { scrollTop: $(".item").eq(1).offset().top },
      1000
    );
  });

$(".link")
  .eq(2)
  .on("click", function () {
    $("html, body").animate(
      { scrollTop: $(".item").eq(2).offset().top },
      1000
    );
  });

2

Answers


  1. By using .each over the .link, you can get a reference to both the link in question and to the index being iterated over, which can be used to get to the .item you want.

    const items = $(".item");
    $('.link').each(function(i) {
      $(this).on('click', function() {
        $("html, body").animate(
          { scrollTop: items.eq(i).offset().top },
          1000
        );
      });
    });
    
    Login or Signup to reply.
  2. Consider the following.

    $(function() {
      $(".link").click(function() {
        $("html, body").animate({
            scrollTop: $(".item").eq($(this).index()).offset().top
          },
          1000
        );
      });
    });
    

    Using this can allow you to reference the clicked element. $(this).index() get’s the index of the clicked element.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search