50projects50days/background-slider/script.js

41 lines
782 B
JavaScript
Raw Normal View History

2020-10-05 22:06:24 +00:00
const body = document.body
const slides = document.querySelectorAll('.slide')
const leftBtn = document.getElementById('left')
const rightBtn = document.getElementById('right')
let activeSlide = 0
rightBtn.addEventListener('click', () => {
activeSlide++
if (activeSlide > slides.length - 1) {
activeSlide = 0
}
setBgToBody()
setActiveSlide()
})
leftBtn.addEventListener('click', () => {
activeSlide--
if (activeSlide < 0) {
activeSlide = slides.length - 1
}
setBgToBody()
setActiveSlide()
})
setBgToBody()
function setBgToBody() {
body.style.backgroundImage = slides[activeSlide].style.backgroundImage
}
function setActiveSlide() {
slides.forEach((slide) => slide.classList.remove('active'))
slides[activeSlide].classList.add('active')
}