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');
});
});
Using document.getElementById:
let link = document.createElement("a");
var linkText = document.createTextNode(images[i].name);
let eventListenerFunction =
document.getElementById('formatted-ticket-content').forEach(linkText =>
{
linkText.addEventListener("click", (e) => {
log('A link was clicked');
} );
});
2
Answers
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.
Add the event listener to the link text:
Then you will have one event listener on each
linkText
. I don’t know what alinkText
is, so I don’t know if this is what you wantYou’re adding the listener multiple times to the same element.
Assuming the elements you click have the class "awsui_tabs-content":
Try something like this: