Simple question about for loop

2

I have 4 images: one image over the other within div . It is over each other because it is in absolute position. I would like to make a simple slideshow , just to learn its basic operation inside a loop . What's wrong with the code below?

(Note: The whole code is available here )

$(document).ready(function() {

    for ($n = 0; $n < 3; $n++) {
        $('img:eq($n)').fadeToggle().delay(3000).fadeToggle();
    }      
});
    
asked by anonymous 07.06.2016 / 00:37

1 answer

4

I think you're not looking for a loop, but a setInterval:

$('.item:gt(0)').hide(); // esconder todos os items cujo index é maior que 0, só o primeiro fica visível
var countItems = $('.item').length; // num de .item que temos
var next;
var slide = setInterval(function() {
    next = $('.item:visible').index() + 1; // ver qual é o item que está visivél, saber o seu index e somar um, que vai ser o proximo .item a aparecer
    if(next >= countItems) { // caso o next seja maior ou igual do que o numero total de .item
    	next = 0; // o proximo .item a aparecer vai ser o primeiro, cujo index é 0
    }
    $('.item').fadeOut();
    $('.item:eq(' +next+ ')').fadeIn(); // aparecer o proximo .item, definido pela var next
}, 1500); // definir tempo entre cada slide
.item {
  position:absolute;
  width:100%;
  height:200px;
  background-repeat:no-repeat;
  background-size:cover;
  background-position:center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divid="marco">
  <div class="item" style="background-image: url(https://i.ytimg.com/vi/5UmFIcqYO9w/hqdefault.jpg)">
  
  </div>
  <div class="item" style="background-image: url(https://i.ytimg.com/vi/mi6Yb_HPS9A/hqdefault.jpg)">
  
  </div>
  <div class="item" style="background-image: url(https://i.ytimg.com/vi/0MyTHD24HKs/hqdefault.jpg)">
  
  </div>
  <div class="item" style="background-image: url(https://i.ytimg.com/vi/hQTsb64ZuFo/hqdefault.jpg)">
  
  </div>
</div>

EXAMPLE in jsfiddle , this way everyone will have the same dimensions, just adjust the length (width) and height (height ) that wants to .item

    
07.06.2016 / 11:24