skip to Main Content

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


  1. 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');
      } );
    });
    
    Login or Signup to reply.
  2. You’re adding the listener multiple times to the same element.

    Assuming the elements you click have the class "awsui_tabs-content":

    <div class="awsui_tabs-content">...</div>
    

    Try something like this:

    document.querySelectorAll('[class^="awsui_tabs-content"]').forEach(linkElement => {
      linkElement.addEventListener("click", (clickEvent) => {
        log('A link was clicked: ' + linkElement.className);
      });
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search