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

Why does addEventListener is sending logs 6 times whenever I click a hyperlink in a page?

my addEventListener is sending logs 6 times whenever I click a hyperlink in a page. I have been checking what causing it and I couldn’t figure out why. I know there are similar questions like this in this forum but I don’t know why it’s sending 6 logs to my webhook url. Appreciate all the help I can get. Thank you very much in advance.

My code:

let link = document.createElement("a");
var linkText = document.createTextNode(images[i].name);

document.querySelectorAll('[class^="awsui_tabs-content"]').forEach(linkText => {
  link.addEventListener("click", (e) => {
    log('A link was clicked');
  });
});

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 :

Because you are adding 6 event listeners to the onClick of the link.

I can think of two ways to solve this depending on what you are trying to do. Because I’m not sure, I’ll just give you both, but I’d advise you clarify your question.

PS: I have also renamed one of your variables to reduce confusion because you had one variable that was being named twice.

Stop the same eventListener being added more than once

if you define the eventListener function once, it won’t be added multiple times. it will just be added once.

let link = document.createElement("a");
let imageNameTextNode = document.createTextNode(images[i].name);
let eventListenerFunction = (e) => {
    log('A link was clicked');
  }
document.querySelectorAll('[class^="awsui_tabs-content"]').forEach(linkText => {
  link.addEventListener("click", eventListenerFunction );
});

Add the event listener to the link text:

Then you will have one event listener on each linkText. I don’t know what a linkText is, so I don’t know if this is what you want

let link = document.createElement("a");
let imageNameTextNode = document.createTextNode(images[i].name);
let eventListenerFunction = 
document.querySelectorAll('[class^="awsui_tabs-content"]').forEach(linkText => {
  linkText.addEventListener("click", (e) => {
    log('A link was clicked');
  } );
});
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