As a newcomer to JS, I've taken on the challenge of creating a size comparison tool for practice. In my HTML file, I have multiple buttons representing different US sizes that should display the corresponding UK, EU, and CM size when clicked inside a designated <div>
.
In my current implementation, I've assigned unique IDs to each button and written separate functions for each, which has resulted in inefficient and repetitive code. I'm now seeking a more streamlined approach to make my code more efficient.
const sizeAll = [
{ US: 4, UK: 3.5, EU: 36, CM: 22 },
{ US: 4.5, UK: 4, EU: 36.5, CM: 22.5 },
//other size objects removed from here
{ US: 14, UK: 13, EU: 48.5, CM: 32 }
];
// Size elements
let sizeElements = document.querySelectorAll('.size-button');
let us = document.getElementById('current');
let uk = document.getElementById('uk');
let ukNumber = document.getElementById('ukNumber');
let eu = document.getElementById('eu');
let euNumber = document.getElementById('euNumber');
let cm = document.getElementById('cm');
let cmNumber = document.getElementById('cmNumber');
size.forEach(function(sizeElement, index) {
sizeElement.addEventListener('click', function() {
us.textContent = 'US' + ' ' + sizeAll[index].US + ':';
uk.textContent = 'UK';
ukNumber.textContent = sizeAll[index].UK;
eu.textContent = 'EU';
euNumber.textContent = sizeAll[index].EU;
cm.textContent = 'CM';
cmNumber.textContent = sizeAll[index].CM;
});
});
<div class="buttons">
<button class='size-button' value="4">4</button>
<button class='size-button' value="4.5">4.5</button>
<!--I took out all other buttons for demonstration purposes-->
<button id='Fourteen' value="14">14</button>
</div>
<div>
<h2 id="current"></h2>
<h3 id="uk"></h3>
<p id="ukNumber"></p>
<h3 id="eu"></h3>
<p id="euNumber"></p>
<h3 id="cm"></h3>
<p id="cmNumber"></p>
</div>
To avoid unnecessary repetition, I am looking for an efficient way to handle this code instead of writing out individual functions like comparison45()
, comparison5()
, etc., for each button.