0

I've worked with event delegation in the past but for some reason I'm having trouble setting up a single event listener that executes one of three functions depending on the ID of the element clicked.

Here's the code without event delegation:

eventListeners: function() {
    document.getElementById("button-1").addEventListener('click', 
function() {
      shuffler.reset1();
      shuffler.displayCards();
    });
    document.getElementById("button-2").addEventListener('click', function() {
      shuffler.reset2();
      shuffler.displayCards();
    });
    document.getElementById("button-3").addEventListener('click', 
function() {
      shuffler.reset3();
      shuffler.displayCards();
    });

I've tried using something along the lines of:

document.getElementsByClass("button").addEventListener('click', function 
() {
if (event.target.id == "button-1") {
shuffler.reset1();
}
});
Graham
  • 47
  • 5
  • Possible duplicate of [javascript adding click event listener to class](https://stackoverflow.com/questions/21700364/javascript-adding-click-event-listener-to-class) – Daan Jun 21 '19 at 06:50
  • `getElementsByClass()` isn't valid JavaScript, maybe you meant `getElementsByClassName()`? You would still have to loop through all elements, because it returns an array-like element. – Daan Jun 21 '19 at 06:52

1 Answers1

0

Attach the listener to the container that contains all buttons. Then, I'd use an object indexed by id, and check if the id of the element that was clicked exists in the object - if so, run the function:

const fns = {
  'button-1': () => {
    shuffler.reset1();
    shuffler.displayCards();
  },
  // ...
}

document.querySelector('< something that contains all buttons >').addEventListener('click', ({ target }) => {
  const { id } = target;
  if (fns[id]) {
    fns[id]();
  }
});

Note that in this particular case, you can use just one function by checking the last number in the ID:

document.querySelector('< something that contains all buttons >').addEventListener('click', ({ target }) => {
  const { id } = target;
  if (id.startsWith('button-')) {
    const buttonNum = id.match(/\d+/)[0];
    shuffler['reset' + buttonNum]();
    shuffler.displayCards();
  }
});
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320