Rain
Rain

Reputation: 139

Array in jQuery does not work

I have an array in jQuery like this

var matches = [];
  jQuery(".block").each(function() {
  matches.push(this);
});

Now I want to use the matches array like this

var len = jQuery(matches).length;
for (var i = 0; i < len; i++){
  function slider() {
    jQuery(matches[i]).show("slow");
    jQuery(matches[i]).animate({left:'+=730'},3000);
    jQuery(matches[i]).show("normal", slider);
  }
}

When I put number in the place of I, it works, but the for loop is not working. Please help me where the mistake.

Upvotes: -1

Views: 85

Answers (2)

LordZardeck
LordZardeck

Reputation: 8283

Ss the commenter said, you have it wrapped in a functon thats not called. Also, i tested it, wrapping jquery around the array has no effect, so that's not the problem. Also, is there any reason you are not executing that code in the each function? Try this instead:

jQuery(".block").each(function() {
    jQuery(this).show("slow");
    jQuery(this).animate({left:'+=730'},3000);
    jQuery(this).show("normal", slider);
});

You could even chain them together like so:

jQuery(".block").each(function() {
    jQuery(this).show("slow", function(){jQuery(this).animate({left:'+=730'},3000, function(){jQuery(this).show("normal", slider);});});
});

One final note, if this is an effect you are using multiple different times, you could wrap the effect in a function and call it in the iteration:

jQuery(".block").each(function() {
    slider(this);
});
function silder(el)
{
     jQuery(el).show("slow", function(){jQuery(el).animate({left:'+=730'},3000, function(){jQuery(el).show("normal", slider);});});
}

Upvotes: 3

Reinstate Monica Cellio
Reinstate Monica Cellio

Reputation: 26143

Try this...

for (var i= 0; i< matches.length; i++){
    jQuery(matches[i]).show("slow");
    jQuery(matches[i]).animate({left:'+=730'},3000);
    jQuery(matches[i]).show("normal", slider);
}

It's more likely that you want to replace the whole of your example code with just this...

jQuery(".block").each(function() {
    jQuery(this).show("slow");
    jQuery(this).animate({left:'+=730'},3000);
    jQuery(this).show("normal", slider);
});

With that you don't need to declare or use an array. Obviously if there's a reason you're doing it that way then fair enough, but it does seem unnecessary.

There will be conflicts between the 2 show functions though.

Upvotes: 1

Related Questions