Proper way to handle many event listeners in javascript

Tags: ,



In my website, I have a dynamically growing list, (from a database) that has buttons attached to each item of the list. The button goes to the same javascript function, but each element in the list has a different id, which needs to be included inside the function when it is running.

I’m currently using onclick in the html and can pass the id through the function’s parameter, as I am using template literals to render the list.

Is there any way that I can do this with event listeners?

An example of what I currently have would be:

onclick="theFunction('id')"

which changes for every item in the list, so the list could look like

<ul>
<li onclick="theFunction('id1')">name1</li>
<li onclick="theFunction('id2')">name2</li>
<li onclick="theFunction('id3')">name3</li>
</ul>

Answer

Use event delegation instead: attach one listener to the <ul>, and then on click, check to see if the clicked element was a <li>. If so, check an attribute of the <li> to figure out what parameter to call theFunction with. For example:

const theFunction = console.log;

document.querySelector('ul').addEventListener('click', (e) => {
  if (!e.target.matches('li')) {
    return;
  }
  const param = 'id' + e.target.dataset.param;
  theFunction(param);
});
<ul>
  <li data-param="1">name1</li>
  <li data-param="2">name2</li>
  <li data-param="3">name3</li>
</ul>

Note how the onclick attributes have been replaced with data-param attributes.



Source: stackoverflow