In my current project, I have set up functionality to toggle classes on a table for hiding specific columns. This is determined by checkboxes selected by the user above the table, each checkbox having its own unique ID like "product_1", "product_2", and so on.
Since there are 4 columns in the table, I created individual functions for 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 toggled classes are responsible for controlling the visibility of columns.
Although this setup is functional, I am aware that I essentially have repetitive CSS classes and JavaScript functions catering to each checkbox's unique class. I'm interested in exploring more efficient methods with fewer repetitions. Any suggestions?