I am toggling classes on a table to hide specific columns, based on checkboxes that are selected by the user above the table. The checkboxes have IDs "product_1", "product_2" etc.
There are 4 columns in the table, so I made 4 functions that do the toggling:
const toggleFirst = document.getElementById('product_1').addEventListener('click', () => {
document.querySelector('#compare-table').classList.toggle('tb-compare-hide-1');
});
const toggleSecond = document.getElementById('product_2').addEventListener('click', () => {
document.querySelector('#compare-table').classList.toggle('tb-compare-hide-2');
});
const toggleThird = document.getElementById('product_3').addEventListener('click', () => {
document.querySelector('#compare-table').classList.toggle('tb-compare-hide-3');
});
const toggleFourth = document.getElementById('product_4').addEventListener('click', () => {
document.querySelector('#compare-table').classList.toggle('tb-compare-hide-4');
});
The classes that are toggled then control the showing/hiding.
I have this working, but I have 4 CSS classes, and 4 JS functions, that are basically doing the same thing but with a different checkbox relating to a different class.
Can I achieve this with fewer repetitive classes and functions?
You can remove the ID from the checkboxes and use classes instead. To map the checkboxes to the column you can use the data
attribute`
<input type="checkbox" class="product" data-column-number="1">
<input type="checkbox" class="product" data-column-number="2">
<input type="checkbox" class="product" data-column-number="3">
<input type="checkbox" class="product" data-column-number="4">
const elementCompareTable = document.querySelector('#compare-table');
document.querySelector('.product').addEventListener('click', (event) => {
const numberTarget = event.target.dataset.columnNumber;
elementCompareTable.classList.toggle(`tb-compare-hide-${numberTarget}`);
});