Search code examples
javascriptcounter

Set limit on button click, store value and display value on refresh using localstorage


I have multiple buttons on a page with the same class, I am trying to set a limit of 3 clicks and display "maximum selection" text once 3 clicks have been made on the button.

if the visitor goes back to the page I want these values to be saved and still displayed.

Currently the reset function resets the counter back to 0, but after that I am able to select more than 3 selections and the counter goes past 3, I'd like 3 to be the limit.

JSFiddle: https://jsfiddle.net/80rhzjwq

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>



JS

/ 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;
  
});

    }


}

Solution

  • Here is a simpler and working solution

    Note I delegate from a button container

    https://jsfiddle.net/mplungjan/wzmh08ek/

    window.addEventListener("DOMContentLoaded", () => {
      const max = 3;
      let clickCounterValue = +localStorage.getItem("clickCounter"); // value or 0
      const clickCounter = document.getElementById("clickCounter")
      const boxContainer = document.getElementById("boxContainer");
      const boxes = boxContainer.querySelectorAll(".box");
      const msg = document.getElementById("msg");
      const resetButton = document.querySelector(".reset");
      const show = () => {
        const maxReached = clickCounterValue >= max;
        clickCounter.textContent = maxReached ? "Maximum reached" : clickCounterValue;
        boxes.forEach(elem => {
          elem.disabled = maxReached;
        });
        msg.hidden = !maxReached;
      };
      show();
    
      // This function increases the count
      boxContainer.addEventListener('click', (e) => {
        const tgt = e.target.closest(".box");
        if (!tgt) return; 
        // Increment the count by 1
        clickCounterValue++;
        localStorage.setItem("clickCounter", clickCounterValue);
        show();
      });
    
      // Reset local storage to 0
      resetButton.addEventListener("click", () => {
        localStorage.setItem("clickCounter", 0);
        // Write the value to the div
        clickCounterValue = clickCounter.textContent = 0;
        show();
      });
    });
    
    <div id="boxContainer">
      <button class="box">CLICKS: </button>
      <button class="box">CLICKS: </button>
      <button class="box">CLICKS: </button>
    </div>
    <p>SELECTION COUNTER:</p>
    <div id="clickCounter"></div>
    <div id="msg" hidden>Max message</div>
    
    
    <button class="reset">Reset count</button>