0

Hi im trying to make a slideshow that run automatically and with this code it's working but i need to add a Play/Pause button to that code. Someone care to help ? I would need the html/css also

var indexDiaporama=1;
afficherDiapo(indexDiaporama);

function ajoutDiapo(n){
afficherDiapo(indexDiaporama+=n);
}

function diapoActuelle(n){
afficherDiapo(indexDiaporama=n);
}

function afficherDiapo(n){

var i;
var slides=document.getElementByClassName("diapo");
var dots=document.getElementByClassName("dot");

if(n>slides.length){indexDiaporama=1;}

if(n<1){indexDiaporama=slides.length;}

for(i=0; i<slides.length; i++){

slides[i].style.display="none";
}

for(i=0; i<dots.length; i++){

dots[i].className=dots[i].className.replace("active", "");
}

slides[indexDiaporama-1].style.display="block";

dots[indexDiaporama-1].className+="active";
}

var timer = setInterval(function(){
indexDiaporama++;
afficherDiapo(indexDiaporama);
},3000);

1 Answers1

0

Start by setting a variable, we will call it pause, to false and then run a conditional inside your setTimeout() that checks if it is false => if(!paused){ //run code }.

Handle the paused variable due to what state your button is in when it is pressed ==> e.target

You create a function that passes in your event target of a pause/play button when it is clicked. In that function you check the value of your pause/play button, you can use a dataset to toggle 0 or 1 / on or off / true or false on click and change the value of your pause variable due to what that dataset is set to on click.

In my example I use 0 and 1 in the data-id attribute => dataset.id in JS, with a conditional that checks that value => if (e.target.dataset.id === '0'){ //set paused to true }else{ // set paused to false }. Within the conditional I also set the textContent of the button and the dataset.id value as well.

Then each time you press the pause button the setInteral freezes as it is looking for paused to not be set to false => if (!paused){ // run code for setInterval }.

Below is a simply JS setInterval that increments a number by one every millisecond. We can pause and play it using the function and event listener as described above.

const display = document.getElementById('display')
const btn = document.querySelector('.btn')

let paused = false;
let i = 1;

function checkBool(e) {
  if (e.target.dataset.id === '0') {
    e.target.dataset.id = '1'
    btn.textContent = 'Play'
    paused = true;
  }else{
    e.target.dataset.id = '0'
    btn.textContent = 'Pause'
    paused = false;
  }
}

btn.addEventListener('click', checkBool)

const timer = setInterval(function() {
  if (!paused) { //<-- paused is not false
    //<-- run the code your interval handles
    display.textContent = i;
    i++;
  }
}, 100);
<div id="display"></div>
<button class="btn" data-id="0">Pause</button>
dale landry
  • 7,831
  • 2
  • 16
  • 28