Reputation: 12512
How do I determine the index number of the element which text label matches to the one clicked?
I have a list:
<ul>
<li data-cont="item one">this is one</li>
<li data-cont="item 2">this is second</li>
<li data-cont="one more">this is another one</li>
</ul>
...
<div>item one</div>
<div>item 2</div>
<div>one more</div>
When one of LIs is clicked my screen needs to scroll down to one of the matched DIVs later on the page.
$('#li').click(function(){
var scrollNow = $(this).attr('data-cont');
$('html, body').animate({
scrollTop: $(
// here I need to scroll down to the item by index...
).offset().top
}, 500);
});
Upvotes: 1
Views: 207
Reputation: 382434
Getting the index of the div is easy :
var index = $('div').filter(function(){
return $(this).text().trim()==scrollNow}
).index();
(I don't use :contains
as it could match too many div)
But I fail to see why you want this index.
If you want to scroll to the div, you just need to do
var div = $('div').filter(function(){
return $(this).text().trim()==scrollNow}
);
$('html, body').animate({
scrollTop: div.offset().top
}, 500);
Upvotes: 1