document.addEventListener("DOMContentLoaded", () => { const electionData = JSON.parse(document.querySelector('#election-data').innerHTML) function getMaxResult() { return Math.max.apply( Math, Object.values(electionData.parties).map( party => Math.max.apply(Math, party.results) ) ) } Object.keys(electionData.parties).forEach(party => { bar = document.createElement('div') bar.classList.add('bar'); [...document.querySelectorAll('.election-results .bars')].forEach(el => el.appendChild(bar.cloneNode(true))) legend = document.createElement('div') legend.classList.add('legend-item') legendParty = document.createElement('span') legendParty.classList.add('party') legendParty.innerText = party legend.appendChild(legendParty) legendResult = document.createElement('span') legendResult.classList.add('result') legendResult.innerText = 0 legend.appendChild(legendResult); [...document.querySelectorAll('.election-results .legend')].forEach(el => el.appendChild(legend.cloneNode(true))) }) function setCycle(cycle) { [...document.querySelectorAll('.election-results')].forEach(er => { er.querySelector('.year').innerText = electionData.years[cycle]; bars = er.querySelectorAll('.bar'); console.log(er); [...er.querySelectorAll('.legend-item')].forEach((el, idx) => { data = electionData.parties[el.querySelector('.party').innerText] el.querySelector('.result').innerText = data.results[cycle] bars[idx].style.height = (data.results[cycle] / getMaxResult() * 100) + '%' bars[idx].style['background-color'] = data.color }) }) } setCycle(0) Reveal.addEventListener('fragmentshown', e => { if (e.fragment.hasAttribute('data-cycle')) setCycle(e.fragment.getAttribute('data-cycle')) }); Reveal.addEventListener('fragmenthidden', e => { if (e.fragment.hasAttribute('data-cycle')) setCycle(e.fragment.getAttribute('data-cycle') - 1) }); })