Reputation: 1079
I'm trying to click a link and scroll to a tab that exists on my page. The issue is the id I am scrolling to exists twice on the page. When I click the scroll trigger it is scrolling to the id after the one I want to scroll to. is there a way to use closest() or find the next tab with the specific ID?
jquery:
$('.link-to-management').click(function(e) {
e.preventDefault();
var linkTo = $(this).attr('href');
$('html,body').animate({scrollTop:
$(linkTo).offset().top - 55
},350);
});
html:
<a href="#to-management-tab" class="link-to-management">
Assess response, adjust, and review</a>
div scrolling to:
<div class="tab-scroller__nav" id="to-management-tab"></div>
Upvotes: 0
Views: 380
Reputation: 621
As you already know by the comments, multiple elements with the same ID is bad. Really bad. But I do understand that part of it is not under your control.
So in that case, what I would do is tweaking the code a bit to work without ID's:
$('.link-to-management').click(function(e) {
e.preventDefault();
var linkTo = $(this).attr('href');
$('html,body').animate({scrollTop:
$('[data-id=" + linkTo + "]').first().offset().top - 55
},350);
});
<a href="#to-management-tab" class="link-to-management">
Assess response, adjust, and review</a>
...
<div class="tab-scroller__nav" data-id="#to-management-tab"></div>
Not much, if you really need to know. Just changed the id
into data-id
so you don't get punished for using same ID twice, updating the jQuery selector so it can handle the new data-id
attribute, and adding first()
so it chooses the first element as you mentioned.
Upvotes: 1