KolaCaine
KolaCaine

Reputation: 2187

Infinite carousel - with setInterval

Please you can check this code :

I have a problem when I want to remove move class

let lis = document.querySelectorAll('li')
let arr =  [];

for (let i = 0; i < lis.length; i++) {
	arr.push(lis[i]);
}

setInterval( function () {
		let splice = arr.splice(0,1);
    splice[0].classList.add('move');
    arr.push(splice[0]);
},3500)
.red {
  background-color: red;
}
.green {
  background-color: green;
}
.yellow {
  background-color: yellow;
}
.blue {
  background-color: blue;
}

.slideshow {
   width: 350px;
   height: 200px;
   overflow: hidden;
   border: 3px solid #F2F2F2;
}

.slideshow ul {
    /* 4 images donc 4 x 100% */
   width: 400%;
   height: 200px;
   padding:0; margin:0;
   list-style: none;
   transition: 2s;
}
.slideshow li {
   float: left;
   width: 25%;
   height: 200px;
   transition: .5s;
}
.move {
  margin-left: -25%;
  transition: .5s;
}
<div class="slideshow">
	<ul>
		<li class='red'></li>
		<li class='green'></li>
		<li class='yellow'></li>
		<li class='blue'></li>
	</ul>
</div>

Thanks a lot

EDIT

https://jsfiddle.net/o00nu4w8/

With console.log, I have the good effect as I want, but any animation appears

Upvotes: 0

Views: 302

Answers (1)

Temani Afif
Temani Afif

Reputation: 272762

You may try something like this. Use an index that you increment in each step and when you reach the last on you remove all the move classes and you start again.

let lis = document.querySelectorAll('li')
let c = 0;


setInterval(function() {
  if (c == lis.length -1) {
    c = 0;
    for (let i = 0; i < lis.length; i++)
      lis[i].classList.remove('move');
  } else {
    lis[c].classList.add('move');
    c++;
  }
}, 3500)
.red {
  background-color: red;
}

.green {
  background-color: green;
}

.yellow {
  background-color: yellow;
}

.blue {
  background-color: blue;
}

.slideshow {
  width: 350px;
  height: 200px;
  overflow: hidden;
  border: 3px solid #F2F2F2;
}

.slideshow ul {
  /* 4 images donc 4 x 100% */
  width: 400%;
  height: 200px;
  padding: 0;
  margin: 0;
  list-style: none;
  transition: 2s;
}

.slideshow li {
  float: left;
  width: 25%;
  height: 200px;
  transition: .5s;
}

.move {
  margin-left: -25%;
  transition: .5s;
}
<div class="slideshow">
  <ul>
    <li class='red'></li>
    <li class='green'></li>
    <li class='yellow'></li>
    <li class='blue'></li>
  </ul>
</div>

Upvotes: 1

Related Questions