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
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.Consider the following.
Using
this
can allow you to reference the clicked element.$(this).index()
get’s the index of the clicked element.