Simple doubt about for loop

Asked

Viewed 158 times

2

I have 4 images: one image on the other inside a div. It’s on top of each other because it’s in position absolute. I’d like to make a slideshow simple, just to learn its basic functioning within a loop. What’s wrong with the code below?

(Note: All code is available here)

$(document).ready(function() {

    for ($n = 0; $n < 3; $n++) {
        $('img:eq($n)').fadeToggle().delay(3000).fadeToggle();
    }      
});

1 answer

4


I believe you are not looking for a loop, but rather for 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>
<div id="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 all will have the same dimensions, just adjust the length (width) and height (height) you want in .item

  • Look! Thanks! This gave me a new way of thinking my codes! Really works better!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.