<button class="btn">Button n.1</button>
<button class="btn">Button n.2</button>
<button class="btn">Button n.3</button>
.btn { display: block }
const onClick = event => {
// use Event object to get a reference
// to the button that was clicked
const element = event.target
// use the "dataset" API to read/write
// data into the element
const data = element.dataset
// try to read the current counter value
// from the element's data (new API)
// with a ternary conditional operator.
//
// NOTE: element's data are always strings
// so we need to convert it to a number
//
// In case there is not "count" available
// it means it is the first click, so
// we instanciate a default value of "1".
// This is usually called "base condition"
const count = data.count
? Number(data.count)
: 1
// Update the button's text with the
// counter value:
element.innerHTML = `click count: ${count}`
// Write back the new counter value to
// the element, so next click it will be
// correctly remembered and displayed
data.count = count + 1
}
const addOnClick = element =>
element.addEventListener('click', onClick)
document
.querySelectorAll('.btn')
.forEach(addOnClick)
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.