0

Here's my fiddle: http://jsfiddle.net/bzoyc64m/

What I'm trying to achieve:

I want the images to fade in and out, right now, it's half working. The initial fades are fine, but when it comes to the second part it just doesn't seem to work.

So if $('.img-' + i + ' .active[rel="1"]') - remove the active class and fade out AND then fade in the next img and add active class - This works

The next stage is the issue - if $('.img-' + i + ' .active[rel="2"]') do the exact same, but for the previous banner. -This doesn't work

Here's my if statement, where I think I'm doing something wrong. I have no idea what though!!

if($('.img-' + i + ' .active[rel="1"]')) {
    console.log("1");
    $('.img-' + i + ' .active[rel="1"]').fadeOut().removeClass('active').next('img').fadeIn().addClass('active');
}
else if($('.img-' + i + ' .active[rel="2"]')) {
    console.log("2");
    $('.img-' + i + ' .active[rel="2"]').fadeOut().removeClass('active').prev('img').fadeIn().addClass('active');
}

Also - Out of interest. my i is a random number. Is there any way to prevent that from being the same number twice in a row? So for example, prevent it from doing something like this: 1, 2, 5, 4, 4, 4, 2, 3.

Thanks for any help, it's really appreciated!

Nick
  • 3
  • 1

1 Answers1

1

The problem is in your if statement. The statement if($('.img-' + i + ' .active[rel="1"]')) {} is always executed. Even though $(selector) does not matches any DOM element, it returns an empty array, which is regarded as true.

if ([])
    alert("Empty array is true");

This will show the alert, even if the array is empty. You could check the length of jQuery array instead:

if($('.img-' + i + ' .active[rel="1"]').length>0) {
   ...
}

For the second part of your question, you can use a shuffling algorithm

How to randomize (shuffle) a JavaScript array?

How can I shuffle an array?

After you consume all indexes, generate a new shuffle. You should pay attention the boundary condition though. The last number of previous shuffle may be equal to the first number of current shuffle.

Community
  • 1
  • 1
Ersin Basaran
  • 517
  • 3
  • 8