JQuery returns the number (eq) of a clicked div

So, I am creating a jQuery plugin for a project that allows the client to create multiple jQuery scrollers for each page. I specifically focus on the interface for this question.

In the finished document, it will initialize the div slider. Then it takes the number of images in the slider and creates a small circle button for each image so that the user can click on the circle and go directly to the corresponding image.

I am looking for something that will return the .eq() value of this circle to find out which slide they are trying to get to. $(this).eq() does not work.

+4
source share
3 answers

If the items are siblings, you can do this:

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

If not, you can pass the set selector in which to search for the item.

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

Just put the correct one of them inside the click handler.

+9
source

To get the index, use .index() as follows:

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

If they are not next to each other, use this:

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

.index() returns an index based on 0, just as you went to .eq() . Your question really raises an interesting point, but why .eq() without arguments returns an index ...

+1
source

To extend the effect on Patrick’s answer, you can use the index with the collection for more detail.

Sort of:

 var collection = $("div.slider").find("img"); $("div.slider img").click(function() { var index = $(collection).index(this); }); 
0
source

All Articles