Home > Mobile >  How to make a button in JavaScript execute code only once?
How to make a button in JavaScript execute code only once?

Time:01-15

I created a button that creates a grid. However, clicking on the button repeatedly executes the code repeatedly and I only want it to execute once. The code is below:

inputBtn.addEventListener("click", function () {
  createGrid();
});

function createGrid() {
  for (let i = 0; i < 256; i  ) {
    div = document.createElement("div");
    div.classList.add("grid-child");
    if (gridContainer) {
      randomColor();
    }
    gridContainer.appendChild(div);
  }
}

I created a loop that I thought would stop executing after 256 times. I also tried adding a break at the very end but that led to some other problems.

CodePudding user response:

Set the once option to true when adding the listener:

inputBtn.addEventListener(
  "click",
  function () {
    createGrid();
  },
  { once: true }
);
  • Related