Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading