简体   繁体   中英

Vanilla JS (no jQuery) - How to toggle more than one class at once?

I am dealing with a legacy system and I can't rewrite the whole css.

So I find myself in need to toggle 2 classes on the same element when another one is clicked (imagine clicking on a button to hide/show a modal).

The following is the code for the modal.
Where the modal window is by default .hidden (without the class "visible") and on click it is .visible (without the class "hidden").

 function openModal(modalID) { document.getElementById(modalID) .classList.toggle('hidden'); document.getElementById(modalID) .classList.toggle('visible'); }
 I agree to accept the <a href="#" onclick="openModal('tandcmodal')"> terms and conditions </a> of this website. <div id="tandcmodal" class="hidden"> Content of the modal </div>

So, I believe there must be a way to toggle more than one class at once with .toggle() .
Or isn't it?

Unfortunately, .toggle accepts only one argument : the one class name you wish to toggle. To be DRY, you'll have to iterate over an array of class names, or save the classList in a variable and call .toggle twice:

 function openModal(modalID) { const { classList } = document.getElementById(modalID); classList.toggle('hidden'); classList.toggle('visible'); }
 .hidden { display: none; } .visible { display: block; }
 I agree to accept the <a href="#" onclick="openModal('tandcmodal')"> terms and conditions </a> of this website. <div id="tandcmodal" class="hidden"> Content of the modal </div>

But note that usually there's no need for both a hidden and a visible class. Often you can have just a hidden class, and add it / remove it, letting the default display style take effect when hidden is not active:

 function openModal(modalID) { document.getElementById(modalID).classList.toggle('hidden'); }
 .hidden { display: none; }
 I agree to accept the <a href="#" onclick="openModal('tandcmodal')"> terms and conditions </a> of this website. <div id="tandcmodal" class="hidden"> Content of the modal </div>

Also note that inline attribute handlers behave very strangely, have escaping problems, and are generally considered to be quite poor practice - they should probably be avoided in almost all cases. Consider adding the event listener using Javascript instead:

 document.querySelector('a').addEventListener('click', () => openModal('tandcmodal')); function openModal(modalID) { document.getElementById(modalID).classList.toggle('hidden'); }
 .hidden { display: none; }
 I agree to accept the <a href="#"> terms and conditions </a> of this website. <div id="tandcmodal" class="hidden"> Content of the modal </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM