Im making a slideshow in HTML, and here is my code:
var cur = 0;
var max = $('.slides div').length;
var $curSlide;
setInterval(function() {
$($('.slides div')[cur]).fadeOut(500, function() {
$($('.slides div')[cur%=max, ++cur]).fadeIn(500);
});
}, 2000);
.slides img {
max-width: 400px;
max-height: 300px;
}
.slides div:not(#first) {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="slides">
<div id='first'><img src="https://www.tutorialrepublic.com/lib/images/javascript-illustration.png"></div>
<div><img src="https://upload.wikimedia.org/wikipedia/commons/thumb/6/61/HTML5_logo_and_wordmark.svg/1200px-HTML5_logo_and_wordmark.svg.png"></div>
<div><img src="https://cdn-images-1.medium.com/max/1200/1*OFsc0SD55jhi8cjo7aCA4w.jpeg"></div>
</div>
It works the first time but it won't repeat!!!
It runs through the slides once but can't run again.
What is the problem here?
Ah, the comma operator. Classical error.
In the line:
$($('.slides div')[cur%=max, ++cur]).fadeIn(500);
You are getting the remainder first, then incrementing cur
, whereas what you should be doing, is increment first then get the remainder:
$($('.slides div')[++cur, cur%=max]).fadeIn(500);
That should solve your problem, try it out!