Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save etienne-dldc/db971ad1b27a288dc41051e7b7352b0f to your computer and use it in GitHub Desktop.
Save etienne-dldc/db971ad1b27a288dc41051e7b7352b0f to your computer and use it in GitHub Desktop.
04 - Multiple Counters v2 - Declarative
var body = document.body;
// Some helper
function createElement(type, content) {
var elem = document.createElement(type);
elem.innerText = content !== undefined ? content : null;
return elem;
}
// State
var counters = [0, 0, 0];
// Render
function render() {
// Clean body
body.innerHTML = '';
// Add counter button
var addCounterButton = createElement('button', 'Add counter');
addCounterButton.addEventListener('click', function () { counters.push(0); render(); })
body.appendChild(addCounterButton);
// Break line for readability
body.appendChild(createElement('br'));
// Counters
for (var i = 0; i < counters.length; i++) {
// IIFE to create a scope for index
(function (index) {
// Counter value
var counterValue = createElement('span', counters[i]);
body.appendChild(counterValue);
// Decrease button
var dencreaseCounter = createElement('button', '-');
dencreaseCounter.addEventListener('click', function () {
counters[index] = counters[index] - 1;
render();
})
// Append - only of counter is > 0
if (counters[index] > 0) {
body.appendChild(dencreaseCounter);
}
// Increase button
var increaseCounter = createElement('button', '+');
increaseCounter.addEventListener('click', function () {
counters[index] = counters[index] + 1;
render();
})
// Append + only of counter is < 10
if (counters[index] < 10) {
body.appendChild(increaseCounter);
}
// Break line for readability
body.appendChild(createElement('br'));
})(i);
}
}
// Initial render
render();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment