views:

17

answers:

1

Hi,

If I had two sets of classes, like so

<div class = "link 1"></div>
<div class = "link 2"></div>
<div class = "link 3"></div>
....
<div class = "link x"></div>

and

<div class = "target 1"></div>
<div class = "target 2"></div>
<div class = "target 3"></div>
....
<div class = "target x"></div>

how can i get the nth link to scroll the page to the nth target using jQuery scrollTo? The classes 1, 2, 3.... are dynamically generated.

Thanks.

+2  A: 

You could do it based off .index(), something like this:

$("div.link").click(function() {
   var target = $("div.target").eq($(this).index("div.link"));
   $.scrollTo(target);
});

This uses the .index(selector) overload to get which link we clicked on, then it gets the same index of the div.target set to find the destination using .eq().

Note: if there are other <div> elements with the classes target or link you need to tweak the selectors here so they're only searching the batch you're in, otherwise the indexes may be off.

Nick Craver
Brilliant! Thanks a ton.
pixeltocode