Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

addEventListener to a Button ID

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading