Как перенести setInterval () в метод класса JavaScript
const list = document.querySelector('.js-gallery');
const items = document.querySelectorAll('.gallery__item'); // Use this for slide count, not list
Array.from(list); // Doesn't do anything
class Gallery {
constructor(slideshow) {
this.slideshow = slideshow;
this.slideCount = items.length;
this.items = items[0].getBoundingClientRect().width;
this.currentSlide = 1;
this.slideTransitionInterval = null;
}
transitionSlide() {
console.log('invoked');
if (this.currentSlide < this.slideCount) {
list.style.transform = `translateX(-${this.currentSlide * this.items}px)`;
this.currentSlide += 1;
} else {
this.stopSlideshow();
list.style.transform = `translateX(0)`;
this.currentSlide = 1;
}
}
// Trying to make a method with setInterval() so that the slide runs every 5 seconds.
startSlideshow() {
this.stopSlideshow();
this.slideTransitionInterval = setInterval(this.transitionSlide.bind(this), 500);
}
stopSlideshow() {
if (this.slideTransitionInterval) {
clearInterval(this.slideTransitionInterval);
}
}
}
const pics = new Gallery(list);
pics.startSlideshow();
.title {
width: 100%;
text-align: center;
}
.gallery {
display: flex;
flex-direction: row;
flex-wrap: nowrap;
padding: 0;
transition: all 500ms ease;
}
.gallery-container {
overflow: hidden;
position: relative;
width: 1000px;
margin: 0 auto;
}
.gallery__item {
list-style: none;
height: 500px;
min-width: 1000px;
background-position: center center;
background-size: cover;
}
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="style.css">
<title>Document</title>
</head>
<body>
<h1 class="title">Gallery of Real Cool JS3 Images</h1>
<div class="gallery-container">
<ul class="gallery js-gallery">
<li class="gallery__item js-gallery-item" style="background-image: url('https://picsum.photos/1000/650/?image=1062')"></li>
<li class="gallery__item js-gallery-item" style="background-image: url('https://picsum.photos/1000/650/?image=837')"></li>
<li class="gallery__item js-gallery-item" style="background-image: url('https://picsum.photos/1000/650/?image=1025')"></li>
<li class="gallery__item js-gallery-item" style="background-image: url('https://picsum.photos/1000/650/?image=237')"></li>
</ul>
</div>
<script src="script.js" defer></script>
</body>
</html>
SAMER SAEID