JSFiddle - React, Tailwind, and code Playground
HTML
<button class="box">CLICKS: </button>
<button class="box">CLICKS: </button>
<button class="box">CLICKS: </button>
<p>SELECTION COUNTER:</p><div id='clickCounter'></div>
<button class='reset' onclick="clickReset()">Reset count</button>
JavaScript
// This function increases the count
const boxes = Array.from(document.getElementsByClassName('box'));
let one = 0;
boxes.forEach(box => {
box.addEventListener('click', function clickButtonFunction() {
console.log('run');
//Check to see if the localstorage variable exists. If it does not, this is the first time coming to the page, and we need to initalize it to 0
if (localStorage.getItem("clickCounter") === null) {
// Store
localStorage.setItem("clickCounter", "0");
}
// Get the value from local storage
var value = parseInt(localStorage.getItem("clickCounter"));
// Incrememtnt the count by 1
var newValue = value + 1
//Write the value back to local storage
localStorage.setItem("clickCounter", newValue);
// Write the value to the div
document.getElementById("clickCounter").innerHTML = newValue
one += 1;
if (one === 3){
document.querySelectorAll('.box').forEach(elem => {
elem.disabled = true;
document.getElementById("clickCounter").innerHTML = 'MAXIMUM SELECTION'
});
}
}
);
});
// Reset local storage to 0
function clickReset() {
localStorage.setItem("clickCounter", "0");
// Write the value to the div
document.getElementById("clickCounter").innerHTML = '0'
{
document.querySelectorAll('.box').forEach(elem => {
elem.disabled = false;
});
}
}