tags:

views:

26

answers:

3

So I'm building a jQuery plugin for a project that allows the client to create multiple jQuery scrollers per page -- I'm focusing strictly on the front end for this question.

On document ready, it will tell the slider div to initialize. This then takes the number of images in the slider, and creates a little circle button for each image so a user could click a circle and slide directly to the corresponding image.

I'm looking for something that will return the .eq() value of that circle in order to know which slide they're trying to get to. $(this).eq() does not work.

+1  A: 

If the elements are siblings, you could do this:

var index = $(this).index();

If not, you can pass a selector of the set in which to look for the element.

var index = $(this).index('someSelector');

Just place the proper one of these inside your click handler.

patrick dw
That worked great, thanks!
Michael
@Michael - You're welcome. Remember to accept this answer by clicking the big checkmark to the left if it was helpful.
patrick dw
Just clicked it as soon as it let me. Thanks again!
Michael
A: 

To get the index, use .index() like this:

$("#content > div").click(function() {
   alert($(this).index());
});

If they're not next to each other, use this:

$(".selector").click(function() {
   alert($(this).index(".selector"));
});

.index() returns the 0-based index, just like you'd pass to .eq(). Your question does raise an interesting point though, why doesn't .eq() without arguments return the index...

Nick Craver
A: 

To extend on Patrick's answer, you can use index with a collection for more granularity.

Something like:

var collection = $("div.slider").find("img");
$("div.slider img").click(function() {
 var index = $(collection).index(this);
});
Mike Robinson
Mike - If you're going to use the collection, you need to flip it around. `$(collection).index(this);` :o)
patrick dw
Whoops thanks - I always get those two confused. Fixed.
Mike Robinson