Running Events Once
Open the project folder
In our starter files, open the index.html page from this lessons folder:
04.Events-And-The-DOM > 12.Running-events-once
Adding the once option to addEventListener
We have previously looked at using the addEventListener method, and how we can use it to enable the bubbling or capturing phase. The options object was added to set the capture phase to be true, which looked like this:
// events.js:
button.addEventListener('click', addToFavourites, {capture: true});
Another option we have is to restrict this event to only ever be called once. This is also added to the options object:
const addButtons = document.querySelectorAll(".add");
addButtons.forEach(function(button) {
button.addEventListener('click', addToFavourites, {once: true} );
});
The event listener attaced to the star will now only run once, and any further clicks will revert to the article since the stars event listener is now removed.
This is a great way to add a single use event listener to only ever be called once.