<button class="btn">Button n.1</button>
<button class="btn">Button n.2</button>
<button class="btn">Button n.3</button>
.btn {
display: block;
background: red;
}
/*
This class name is inspired by the BEM convention:
https://seesparkbox.com/foundry/bem_by_example
*/
.btn--clicked {
background: green;
}
const eventHandler = eventContext =>
eventContext.target.classList.toggle('btn--clicked')
const addEventHandler = element =>
element.addEventListener('click', eventHandler)
// Get a reference to a list of elements
// using a CSS selector as matching rule
const allButtons = document.querySelectorAll('.btn')
// Run the "addEventHandler" on every
// item of the "allButtons" list
// ¿ isn't this a cool api ?
allButtons.forEach(addEventHandler)
/*
Very often you would find the code above
all condensed into one single instruction
that uses nested functions.
Also, "eventContext" is often referred as:
- event
- evt
- e
Developers love to shorten names!
document
.querySelectorAll('.btn')
.forEach(element => {
element.addEventListener('click', e => {
e.target.classList.toggle('btn--clicked')
})
})
Don't get scared, it may look a mess right
now, but in time this syntax will become
natural to you, and you will love it in
the end :-)
*/
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.