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.
Asked
Active
Viewed 56 times
2
-
5Does this answer your question? [JavaScript: remove an event listener from within that listener?](https://stackoverflow.com/questions/4936324/javascript-remove-an-event-listener-from-within-that-listener) – Heretic Monkey Jan 13 '21 at 21:06
-
Why don't you simply use a flag? – AbsoluteBeginner Jan 13 '21 at 21:52
-
yes that is what I was looking for Heretic Monkey – Cole Ogden Jan 13 '21 at 22:12
1 Answers
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