Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery returning the number (eq) of a clicked div

Tags:

html

jquery

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.

like image 734
Michael Avatar asked Dec 23 '22 00:12

Michael


2 Answers

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.

like image 51
user113716 Avatar answered Jan 05 '23 00:01

user113716


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...

like image 22
Nick Craver Avatar answered Jan 04 '23 22:01

Nick Craver