JQuery: Selecting index of currently clicked item from inside another element

Hi all,

I’m trying to find the currently clicked index of .accordion_trigger from within another element.

When inside the .accordion_trigger click event I can simply do the below to get the current clicked index:

$('.accordion_trigger').click(function(){
		
var index = $('.accordion_trigger').index(this);		

}
	return false; 
});

Obviously this doesn’t work when called from within another element. I understand that ‘this’ is part of the problem but can’t seem to find a way to form the code in such a way for it to produce a valid result. Thus far I only get -1 or 0.

When .accordion_trigger is clicked it has an “$(this).toggleClass(‘active’).next().slideDown();” applied so in theory I shold be able to search for which of the .accordion_trigger’s are “active”.

I’ve also tried doing this via the below method but to no avail:

var current = $('.accordion_trigger');			 
current.each(function() {
if ($(this).hasClass('active')) {
var index2 = current.index(this);
})

I’m missing a small but vital piece of syntax aren’t I?

Thanks in advance,

Thanks for the shortcut. I was hesitant to go stuffing more than one class/id in the same space because I read somewhere online that if we provide more than one class as once then JQuery will assume only the first class reference.

Just a tip. Instead of


var current = $('.accordion_trigger');			 
current.each(function() {
  if ($(this).hasClass('active')) {
    // do something
  }
);

you can also do:


$('.accordion_trigger.active').each( function() {
  // do something
});

.class1.class2 (note, no spaces anywhere!) selects all elements that have class1 and class2 :slight_smile:

Seems like missing curly braces -


$('.accordion_trigger').click(
  function(){
    var index = $('.accordion_trigger').index(this);		
// }          <-- this one is stray 
    return false; 
  }
);



var current = $('.accordion_trigger');
			 
current.each(
  function() {
    if ( $(this).hasClass('active') ) {
      var index2 = current.index(this);
    }
  }         // closing the function()
);          // a semi colon to end the each() call

So code1 has an extra } while code 2 missed one. If you use firebug or developer tools in Chrome, you can pinpoint these errors on the spot.

Thanks for responding and your suggestions.

I ended up doing it in a one liner via the below:
var index = $(‘.accordion_trigger’).index($(‘.active’));

This works nicely so fingers crossed it’ll stay this way.