Force Toggling a CSS Class

Shuqi Khor
2 min readFeb 24, 2023

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:

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:

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:

$('#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!

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Shuqi Khor
Shuqi Khor

No responses yet