Delegating JS

I'm learning pure JavaScript. I have three buttons that are wrapped in a div. You need to make one handler for these buttons and different actions for clicking on each of them.

<!DOCTYPE html>
<html lang="en">
<head></head>

<body>
  <div id="menu">
    <button data-color="day">День</button>
    <button data-color="night">Ночь</button>
    <button data-color="red">Красный</button>
  </div>
</body>

All buttons should make an alert with the innerHTML content when clicked. Interesting performance using the new standard ES6 and higher.

Author: Daniil Kedrov, 2019-08-06

4 answers

class Menu {
  constructor(node) {
    this.node = node;

    if (!this.node) return;

    this.onClick = this.onClick.bind(this);

    this.node.addEventListener('click', this.onClick, false);
  }

  onClick(e) {
    const button = e.target.closest('button');

    if (!button) return;

    const color = this.getColor(button);

    console.log(color);
  }

  getColor(button) {
    return button.getAttribute('data-color');
  }
}

const root = document.querySelector('#menu');

new Menu(root);
<div id="menu">
  <button data-color="day">День</button>
  <button data-color="night">Ночь</button>
  <button data-color="red">Красный</button>
</div>
 3
Author: meine, 2019-08-06 10:50:58

You need to hang the event on the parent, and the event has an e.target address, which will contain a link to the element that was actually clicked.

let action = console.log
menu.addEventListener('click', e => e.target !== menu && action(e.target.dataset.color))
<div id="menu">
  <button data-color="day">День</button>
  <button data-color="night">Ночь</button>
  <button data-color="red">Красный</button>
</div>
 3
Author: Stranger in the Q, 2019-08-07 11:37:16

const menu = document.querySelector('#menu');

menu.addEventListener('click', (e) => {
  if (e.target.tagName === 'BUTTON') {
    alert(e.target.innerHTML);
  }
});
<div id="menu">
  <button data-color="day">День</button>
  <button data-color="night">Ночь</button>
  <button data-color="red">Красный</button>
</div>
 1
Author: Вадим Лешкевич, 2019-08-06 10:44:28

foo();
function foo() {
  let parent = document.getElementById('menu');
    if(!parent) return;
    
  parent.addEventListener('click', (event) => {
    // Получаем элемент по которому произошел клик
    let target = event.target;
     
     // Проверяем наш ли это элемент
     if(target.tagName == 'BUTTON') {
        let targetVal = target.innerHTML;
        alert(targetVal);
     }
    
  });
  
}
<!DOCTYPE html>
<html lang="en">
<head></head>

<body>
  <div id="menu">
    <button data-color="day">День</button>
    <button data-color="night">Ночь</button>
    <button data-color="red">Красный</button>
  </div>
</body>
 0
Author: , 2019-08-06 10:47:48