Khor Shuqi

Force Toggling a CSS Class

One of the things I found pretty useful when dealing with Bootstrap theme is the ability to force toggle a CSS class with Javascript.

Let’s say, you have a select menu with ‘Other’ option, and you would like to display a text input when ‘Other’ is selected:

Instead of using if-else statement to show or hide the text input, you could simply toggle its visibility with a boolean:

JavaScript
const menu = document.querySelector("#select-product-type");
const otherInput = document.querySelector("#input-other");

menu.addEventListener('change', function (e) {
  otherInput.classList.toggle('d-none', menu.value != 'other');
});

The example above will add .d-none class to the text input when ‘Other’ is not selected. (Note that in Bootstrap, .d-none will hide the element)

Unlike the usual behaviour of toggle(), where the resulting state is the direct opposite of the current state, when a boolean is provided as the 2nd argument of classList.toggle(), the presence of the CSS class will be determined by that boolean.

To put it simply:

JavaScript
element.classList.toggle('text-danger', true); // class will be added if not present
element.classList.toggle('text-danger', false); // class will be removed if present

The same applies to jQuery too but with toggleClass(), where it could be written as such:

JavaScript
$('#select-product-type').change(function (e) {
  $('#input-other').toggleClass('d-none', $(this).val() != 'other');
});

That’s it. Not really a cool trick or something but I just recently discovered this second argument of .toggle() after using .add() and .remove() for so long, stupid me!