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');
  });
});

>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');
  } );
});

Leave a Reply