A Pen by Etienne Deladonchamps on CodePen.
Created
September 10, 2017 09:40
-
-
Save etienne-dldc/db971ad1b27a288dc41051e7b7352b0f to your computer and use it in GitHub Desktop.
04 - Multiple Counters v2 - Declarative
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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