carousel: function(){
var $carouselCr = $('#carousel'),
$tabCr = $('.carouselTabs', $carouselCr),
$itemCr = $('.carouselContents', $carouselCr),
tabAmount = (function(){
if($('a', $tabCr).length === $('.item', $itemCr).length){
return $('a', $tabCr).length;
}else{
throw "error: verschillend aantal tabs vs items";
}
})();
var i = tabAmount;
while(i--){
var item = $($('.item', $itemCr)[i]),
tab = $($('a', $tabCr)[i]);
console.log(item, tab);
$(tab).click(function(){
$('.item', $itemCr).hide();
$(item).show();
})
}
}
As you can see, i’m trying to attach a click event to each ‘tab’, to select each ‘item’. I’m doing something wrong. All the tabs refer to the first item.
If i log $('.item', $itemCr)[i] inside the loop it will return all the different items, not just the first.
Simplified HTML structure
<div id="carousel" class="block">
<div class="carouselTabs">
<a href="#">
</a>
<!-- repeating -->
</div>
<div class="carouselContents">
<div class="item">
</div>
<!-- repeating -->
</div>
</div>
A loop doesn’t create a new variable scope. You need to create the click handler in a separate function, and pass whatever needs to be scoped into that function.
Also note that you should not do DOM selection in a loop. Cache it once outside the loop, and reference it in the loop as I did above.
It seems that there have been some changes to the code from the original question. I’d rewrite the code like this:
Now each
.click()handler is referencing a uniquei, which is the index of the current$a_elselement in the iteration.So for example when a click happens on the
$a_elsat index3,$items.eq(i).show();will show the$itemselement that is also at index3.Another approach is to use event delegation, where you place the handler on the container, and provide a selector to determine if the handler should be invoked.
If you’re using jQuery 1.7 or later, you’d use
.on()…Or before jQuery 1.7, you’d use
.delegate()…This way there’s only one handler bound to the
$tabCrcontainer. It check to see if the item clicked matches the'a'selector, and if so, it invokes the handler.If there are other elements in between the
<a>...</a>elements or the<div class="item">...</div>elements so that the indices don’t naturally match up, we’d need to tweak the.index()call just a bit.