switch case chage button dataset atrribute

I have made a start & the stop button, when I click stop button I need to change the data attribute value to stop, then click again to switch the button console to get ‘start’, but now I’m totally confused about how I make it work! make one function or two.

let stopbutton = document.querySelector(".button");
let stoper = stopbutton.dataset.slideStop //value 'start'
stopbutton.addEventListener("click", function() {
  stopbutton.dataset.slideStop = 'stop';
  switch (stoper) {
    case 'start': {
      console.log('start'); 
    } break;
    case 'stop': {   
      console.log('stop'); /* */
    } break;
  }
});
<button data-slide-stop="start" class="button">stop</button>

>Solution :

You can alternate between "start" and "stop" for both the data attribute and text content of the button by checking the current value of each and setting it to the opposite, like this:

document.querySelector(".button").addEventListener(
  "click",
  ({ currentTarget: btn }) => {
    const toggle = (value) => value === "stop" ? "start" : "stop";
    btn.textContent = toggle(btn.textContent);
    btn.dataset.slideStop = toggle(btn.dataset.slideStop);
    console.log("btn.dataset.slideStop:", btn.dataset.slideStop);
  },
);
<button data-slide-stop="start" class="button">stop</button>

Leave a Reply