50projects50days/image-carousel/script.js

42 lines
773 B
JavaScript
Raw Normal View History

2020-11-05 18:04:55 +00:00
const imgs = document.getElementById('imgs')
const leftBtn = document.getElementById('left')
const rightBtn = document.getElementById('right')
const img = document.querySelectorAll('#imgs img')
2021-08-15 22:50:23 +00:00
let idx = 0
2020-11-05 18:04:55 +00:00
let interval = setInterval(run, 2000)
function run() {
idx++
changeImage()
}
function changeImage() {
if(idx > img.length - 1) {
2021-07-28 20:07:55 +00:00
idx = 0
2021-08-15 22:50:23 +00:00
} else if(idx < 0) {
idx = img.length - 1
2021-07-28 20:07:55 +00:00
}
2021-08-15 22:50:23 +00:00
imgs.style.transform = `translateX(${-idx * 500}px)`
2020-11-05 18:04:55 +00:00
}
function resetInterval() {
clearInterval(interval)
interval = setInterval(run, 2000)
}
rightBtn.addEventListener('click', () => {
idx++
changeImage()
resetInterval()
})
leftBtn.addEventListener('click', () => {
idx--
changeImage()
resetInterval()
2021-08-15 22:50:23 +00:00
})