console.clear();
function my_Func() {
//I have a lot of code in this Function Which Is Confusing
document.querySelector('#return-toggle').addEventListener('click', e => {
return_status = "yes";
alert("Hello!!!!")
});
}
my_Func()
my_Func()
my_Func()
my_Func()
<button id="return-toggle">Display Alert </button>
Basically, I used query selector to trigger id of button. My code requires some function to be called multiple times including the buttons. In my code above, myFunc() is called 3 times but when I click on the Display Alert Button, it alerted 3 times instead of 1 time. I want the button to be triggered 1 time only and not multiple times even if my_Func() is called multiple times. May I know if there is a way to alert() 1 time only when the query selector is called multiple times? I will really appreciate any help I can get 🙂
I am not sure if removing duplicates of query selector will work.
>Solution :
If you pass the same function reference to addEventListener, then the event listener will be considered to have been added only once.
function handleClick(e) {
console.log('click listener');
}
function my_Func() {
document.querySelector('#return-toggle').addEventListener('click', handleClick);
}
my_Func();
my_Func();
my_Func();
my_Func();
<button id="return-toggle">Click</button>
However, in general, you should set up event listeners only once, usually on page load.