)
}
}
)
(
}
{
)
)
(
)
(
(
{
}
)
(
)
}
)
)
{
(
(
)
)
}
)
(
}

Easy Mouse Events

  1. const ui = document.body.appendChild(
  2.   document.createElement('div')
  3. );
  4.  
  5. ui.innerHTML = `
  6.   <button class="hello">say hello</button>
  7.   <button class="make-box">make a box</button>
  8.   <button class="remove-boxes">remove boxes</button>
  9.   <button class="consoleLog red">log in console</button>
  10.  
  11.   <style>
  12.     button { margin: .5em; cursor: pointer; }
  13.     .red { background: red; color: white; }
  14.     .box {
  15.       position: relative;
  16.       float: left;
  17.       width: 30px;
  18.       height: 30px;
  19.       margin: 1em;
  20.       background: blue;
  21.     }
  22.   </style>
  23. `;
  24.  
  25. const actions = {
  26.   hello(e) {
  27.     alert(e.target.className);
  28.   },
  29.  
  30.   ['make-box']() {
  31.     const box = document.body.appendChild(
  32.       document.createElement('div')
  33.     );
  34.     box.classList.add('box');
  35.   },
  36.  
  37.   ['remove-boxes']() {
  38.     const boxes = [...document.querySelectorAll('.box')];
  39.     const num = boxes.length;
  40.     boxes.forEach((el) => el.parentNode.removeChild(el));
  41.  
  42.    alert(
  43.       num === 0
  44.         ? 'no boxes to remove'
  45.         : `removing ${num} box${num > 1 ? 'es' : ''}`
  46.     );
  47.   },
  48.  
  49.   consoleLog(e) {
  50.     console.log('camelCase instead of kebab-case :D');
  51.   },
  52. };
  53.  
  54. document.addEventListener('mousedown', (e) => {
  55.   const action = actions[e.target.classList[0]];
  56.   if (action != null) action(e);
  57. });

This is a powerful little pattern for managing mouse/touch events. Rather than assigning many listeners, this snippet has one listener on the document. Anytime the page is clicked, we look at the event targets classList and use its first value as a key in an actions object.

I have used this or some variation of it many many times over the years. With a little customization it scales well into large projects. I always find myself on the fence about class naming conventions… kebab-case vs camelCase – probably because it just doesn’t matter that much. For large projects, each main section of the UI will have its own document.addEventListener just for organizational purposes.

Variations

The choice to use the first class as the key for the action is pretty arbitrary. Depending on how you like to set things up you could use the last value of the classList, the element id, the element name, or a custom data attribute etc… Like this:

  1. // id
  2. const action = actions[e.target.id];
  3.  
  4. // name
  5. const action = actions[e.target.name];
  6.  
  7. // data attribute <button data-my-id="test">test</button>
  8. const action = actions[e.target.dataset.myId];
// dom // events // javascript // tricks // ui
snippet.zone ~ 2021-24 /// {s/z}