Easy Mouse Events
const ui = document.body.appendChild(
document.createElement('div')
);
ui.innerHTML = `
<button class="hello">say hello</button>
<button class="make-box">make a box</button>
<button class="remove-boxes">remove boxes</button>
<button class="consoleLog red">log in console</button>
<style>
button { margin: .5em; cursor: pointer; }
.red { background: red; color: white; }
.box {
position: relative;
float: left;
width: 30px;
height: 30px;
margin: 1em;
background: blue;
}
</style>
`;
const actions = {
hello(e) {
alert(e.target.className);
},
['make-box']() {
const box = document.body.appendChild(
document.createElement('div')
);
box.classList.add('box');
},
['remove-boxes']() {
const boxes = [...document.querySelectorAll('.box')];
const num = boxes.length;
boxes.forEach((el) => el.parentNode.removeChild(el));
alert(
num === 0
? 'no boxes to remove'
: `removing ${num} box${num > 1 ? 'es' : ''}`
);
},
consoleLog(e) {
console.log('camelCase instead of kebab-case :D');
},
};
document.addEventListener('mousedown', (e) => {
const action = actions[e.target.classList[0]];
if (action != null) action(e);
});
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:
// id
const action = actions[e.target.id];
// name
const action = actions[e.target.name];
// data attribute <button data-my-id="test">test</button>
const action = actions[e.target.dataset.myId];