Home > Back-end >  jQuery loop through multiple eq() instances
jQuery loop through multiple eq() instances

Time:09-17

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 >Link 1</div>
  <div >Link 2</div>
  <div >Link 3</div>
</nav>

<div>
  <div ></div>
  <div ></div>
  <div ></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
    );
  });

CodePudding user response:

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.

CodePudding user response:

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
    );
  });
});
  • Related