skip to Main Content

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>

2

Answers


  1. 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>
    Login or Signup to reply.
  2. You assigned a value to ‘stoper’ at the start and never changed it:

    let stoper = stopbutton.dataset.slideStop //value 'start'
    

    Change that line to:

    let stoper;
    

    to declare the variable globally.
    And then you need to check the button’s dataset EVERY time it is clicked, so in the ‘click’ listener you need to add at the beginning:

    stoper = stopbutton.dataset.slideStop
    

    and then alternate its dataset value like that:

    stopbutton.dataset.slideStop = stoper === 'stop' ? 'start' : 'stop';
    

    Full code will look like that:

    let stopbutton = document.querySelector(".button");
    let stoper;
    stopbutton.addEventListener("click", function () {
      stoper = stopbutton.dataset.slideStop;
      stopbutton.dataset.slideStop = stoper === 'stop' ? 'start' : 'stop';
      switch (stoper) {
      case 'start': {
        console.log('start'); 
      } break;
      case 'stop': {   
        console.log('stop'); /* */
      } break;
    }
    });
    <button data-slide-stop="start" class="button">stop</button>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search