1

I am trying to access the element index during each iteration of this loop.

$('.slide').hide().repeat().each($).fadeIn($).wait(1000, function(){
    //do stuff
}).wait(noHover).fadeOut($);

I tried doing something like:

$('.slide').hide().repeat().each(i, $).fadeIn($).wait(1000, function(){
    alert(i);
}).wait(noHover).fadeOut($);

Clearly I do not understand the right way to do this.

The plugin extension im using:
http://creativecouple.github.com/jquery-timing/examples/pause-cycle-on-hover.html

Heres a fiddle that breaks this down better:
http://jsfiddle.net/zGd8a/

A solution:
http://jsfiddle.net/zGd8a/8/

Dan Kanze
  • 18,485
  • 28
  • 81
  • 134

2 Answers2

2

jsFiddle demo

$('.slide').hide().repeat().each($).fadeIn($).wait(1000, function(){
    var idx = $(this).index();  // here you go!
    $('body').append(idx); //here i need access to index number of element
}).wait(noHover).fadeOut($);
Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313
  • this works, which is awsome. just wondering though - why does the index method need to be called? is there a way to instantiate the index of the element by a parameter similar to each(index, obj) without using a method? – Dan Kanze Oct 21 '12 at 22:27
  • @DanKanze http://jsfiddle.net/zGd8a/3/ With a plugin of mine... ([FadeMe 'FPS'](http://roxon.in/scripts/fademe_jquery_plugin/)) – Roko C. Buljan Oct 21 '12 at 22:46
  • this looks like its going to do the job. i am just a little caught up when binding this function to "slide buttons". ive worked your code into my class to give a better example of what I am trying to do. http://jsfiddle.net/pvvx6/ – Dan Kanze Oct 21 '12 at 23:55
  • @DanKanze http://jsfiddle.net/zGd8a/7/ :) Just added the span buttons generator (for loop) and targeted the parent element and added a click function to spans. :) so simple. And still you can use this only script for multiple sliders and galleries! – Roko C. Buljan Oct 22 '12 at 00:14
  • @DanKanze here is an example with multiple galleries and active class for spans! http://jsfiddle.net/zGd8a/8/ – Roko C. Buljan Oct 22 '12 at 00:33
  • the callback function in the .wait() method also takes parameters: In your case .repeat()...each($)...wait(...,function(i,nr){}); The i is the indexf from .each($), and the nr is the current iteration from .repeat(). So you don't need $(this).index() – peter Oct 22 '12 at 07:44
0

In this case each function takes second parameter (callback function) - $ and does nothing with it. You should place your alert in a body of callback function that is second parameter of each, not wait function. Like this:

$('.slide').hide().repeat().each(function(i, element) {
    alert(i);
}).fadeIn($).wait(1000, function(){
    //do stuff
}).wait(noHover).fadeOut($);

More information here: http://api.jquery.com/each/

roomcays
  • 927
  • 1
  • 7
  • 22