lundi 13 février 2023

How can I improve this JS code? It seems clunky to get each checkbox by ID, then toggle 4 different classes

Thanks in advance.

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 colums 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.

How can I do this in a more elegant way?




Aucun commentaire:

Enregistrer un commentaire