I have a code like this -
<button >New York</button>
<button >Amsterdam</button>
<button >New Jersey</button>
<button >Alabama</button>
<button >Michigan</button>
<button id="undo" >Undo last selection</button>
and have below code to check the order at which these buttons are clicked.
var click = 0;
var buttons = document.querySelectorAll('button.btn');
buttons.forEach(button => {
button.addEventListener('click', function(){
var current = button.innerText;
var existingClicks = current.split(" ");
if(existingClicks.length > 1) {
button.innerText = ` & ${ click}`;
}
else {
button.innerText = `clicked = ${ click}`;
}
});
});
By using the Undo button I want to clear last selection made and should be able to select new button. Any help is appreciated.
CodePudding user response:
Maybe something like this:
let click = 0;
const buttons = document.querySelectorAll('button.btn');
const clicks = [];
buttons.forEach((button, index) => {
button.addEventListener('click', function(){
const clicked = clicks.includes(index);
clicks.push(index);
if (!clicked) {
button.innerText = `clicked = ${ click}`;
} else {
button.innerText = ` & ${ click}`;
}
});
});
document.getElementById('undo').addEventListener('click', () => {
if (!clicks.length) {
return;
}
const lastClicked = clicks.pop();
click--;
let text = buttons[lastClicked].innerText.split('&');
text.pop();
text = text.join('&');
buttons[lastClicked].innerText = text || buttons[lastClicked].getAttribute('data-text');
});
<button data-text="New York">New York</button>
<button data-text="Amsterdam">Amsterdam</button>
<button data-text="New Jersey">New Jersey</button>
<button data-text="Alabama">Alabama</button>
<button data-text="Michigan">Michigan</button>
<button id="undo" >Undo last selection</button>