2

I am currently building a JavaScript tool that takes in an address and runs it through a series of functions that outputs a Boolean value of whether the address is within a range of addresses. From this output the tool will dynamically add cards to the page based on the output. My problem at the moment is that if the event listener is clicked more than once it just continues to add the cards to the page. Is there an event listener that will take in a click event but only fire the first time the event is triggered? If not am I better off just writing a function to remove the click event once it has been fired? I am more than happy to include the code from the project but seemed unnecessary.

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Cole Ogden
  • 67
  • 7

1 Answers1

2

addEventListener has an option to listen for an event only once:

const button = document.querySelector("button");
button.addEventListener("click", onClick, {
  once: true
});

function onClick() {
  window.alert("Clicked!");
}
<button>Try clicking me twice</button>

This option is supported in all major browsers except for Internet Explorer (which has been discontinued)

soimon
  • 2,400
  • 1
  • 15
  • 16