Geek Logbook

Tech sea log book

50projectsIn50days – Day 18: Background Slider

A Image carrousell changes the background image deppending where you clikc. It’s an easy and well known task to perform in your mind but, when you have to use Vainilla Javascript it should be something different.

The first thing you’ll notices is that there is an event listener in the two buttons: right and left. When you click in the right you’ll add one when you click on reft you’ll substract one.

const leftBtn = document.getElementById('left')
const rightBtn = document.getElementById('right')

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()
})

After the arithmetic operations happens the functions: setBgToBody() and setActiveSlides() are call.

function setBgToBody() {
    body.style.backgroundImage = slides[activeSlide].style.backgroundImage
  }

function setActiveSlide() {
  slides.forEach((slide) => slide.classList.remove('active'))

  slides[activeSlide].classList.add('active')
}

They change the style of the code so we can see the changing in the images.

You can see the code in this GitHub Repository: 11.background_slider and the demo of the project is here: Background Slider

Leave a Reply

Your email address will not be published. Required fields are marked *.