I was using the following code to cycle though a set of elements.
$(this).next().show().animate({top: '25px'},250,function(){
$(this).addClass('active');
});
but this was limited as I needed to get to the end of the list of elements, and cycle through again, so I wrote this plugin:
(function($){
$.fn.extend({
rotater: function(class_check){
return this.each(function(){
if($(this).next().hasClass(class_check)){
return $(this).next();
} else {
return $(this).parent().children().first();
}
});
}
});
})(jQuery);
In order to detect when I had reached the end of my desired set (which all share a common class) and if so, grab the first object in which to start the whole cycle again.
I changed the calling code to:
$(this).rotater('common_class').show().animate({top: '25px'},250,function(){
$(this).addClass('active');
});
but it has ceased to work entirely!! I am confused, I could understand if my “return to beginning” script failed, but at least the first cycle should behave exactly as next() did, because I am literally returning the value of next().
My html looks like:
<div id="parent>
<div class="common_class"></div>
<div class="common_class"></div>
<div class="common_class"></div>
<div class="common_class"></div>
<div class="undesired_elemement"></div>
</div>
The return in the
eachcallback has no effect. Your rotator function returns whatevereachreturns, and that is not what the callback returns, but it returnsthisagain.Solution: Don’t use
each:You only have to use
this.eachif you want to apply a functionality to all elements the selector selected.You might experience weird behaviour though if more than one element is selected. In this case you should select the first element explicitly: