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
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:You assigned a value to ‘stoper’ at the start and never changed it:
Change that line to:
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:
and then alternate its dataset value like that:
Full code will look like that: