0

i am trying to create a image slider with autoslide, but stuck at autosliding

here is my javasciprt code my next and prev buttons are working correctly but struggling to automate it

  var myslider=document.querySelector(".image-silder")
    var myimages=document.querySelectorAll(".image-silder img")
    var prevbtn=document.getElementById("prev-btn")
    var nextbtn=document.getElementById("next-btn")
    var optionbtn=document.querySelectorAll(".option")
    console.log(optionbtn)
    var counter=1
    var size=myimages[counter].clientWidth
    myslider.style.transform='translateX('+(-size*counter)+'px)'

    nextbtn.addEventListener("click",function(){
        if(counter>=myimages.length-1)return;
        myslider.style.transition="transform 0.4s ease-in-out"
        counter++
        myslider.style.transform='translateX('+(-size*counter)+'px)'

    })

    prevbtn.addEventListener("click",function(){
        if(counter<=0)return;
        myslider.style.transition="transform 0.4s ease-in-out"
        counter--
        myslider.style.transform='translateX('+(-size*counter)+'px)'

    })
    myslider.addEventListener("transitionend",function(){
        myslider.style.transition="none"

       if(myimages[counter].id==="lastclone")
       {
           counter=myimages.length-2
           myslider.style.transform='translateX('+(-size*counter)+'px)'
       }
    })
    myslider.addEventListener("transitionend",function(){
        myslider.style.transition="none"
       if(myimages[counter].id==="firstclone")
       {
           counter=1
           myslider.style.transform='translateX('+(-size*counter)+'px)'
       }
    })
   optionbtn.forEach((a)=>a.addEventListener("click" ,function(){
   let i=this.getAttribute("option-index")
  counter=i
  myslider.style.transition="none"
  myslider.style.transform='translateX('+(-size*counter)+'px)'
   console.log(counter)
   }))
georg
  • 211,518
  • 52
  • 313
  • 390

2 Answers2

0

Since you have choosen to write the code in Plain JS, you can make use of web APIs. For example, on load (and when all the DOM elements are available), write below code which calls your next button click action every 1 second (or you can change this value too)

setTimeout(function() { //invoke the next button click handler here }, 1000)

So in your case it will be like below

setTimeout(function() { nextbtn.click(); }, 1000)

Check this link too for more details: How can I programmatically invoke an onclick() event from a anchor tag while keeping the ‘this’ reference in the onclick function?

Khazaddoom
  • 66
  • 6
0

You can first of all create a function to go to next slide support principle of DRY, and then use it in the setTimeout function and set the interval after which you want to show next slide. let's say you have a function called nextSlide, and then you can do something like this...

setTimeout(nextSlide,1000);
Uzair Saiyed
  • 575
  • 1
  • 6
  • 16