Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Toggle class on HTML element without jQuery

I have a section on my website which holds all the content, but I want a "sidebar" with hidden content to smoothly appear from the left at the push of an external button.

CSS transitions can handle the smoothness no problem, and jQuery toggle() can switch between classes to move the hidden div in and out of the screen.

How can I get the same effect without using jQuery?

like image 431
KittenCodings Avatar asked Aug 28 '14 08:08

KittenCodings


People also ask

How do you toggle between classes in HTML?

Step 1) Add HTML: Toggle between adding a class name to the div element with id="myDIV" (in this example we use a button to toggle the class name).

How do you toggle a class on an element?

Toggling the class means if there is no class name assigned to the element, then a class name can be assigned to it dynamically or if a certain class is already present, then it can be removed dynamically by just using the toggle() or by using contains(), add(), remove() methods of DOMTokenList object within JavaScript ...

How do you add and remove a class on toggle?

jQuery toggleClass() Method The toggleClass() method toggles between adding and removing one or more class names from the selected elements. This method checks each element for the specified class names. The class names are added if missing, and removed if already set - This creates a toggle effect.

What does classList toggle do?

The classList. toggle() method supports adding and removing CSS classes whether they exist or not in your array with shorter lines of code.


2 Answers

You can implement it only by CSS3:

<label for="showblock">Show Block</label> <input type="checkbox" id="showblock" />  <div id="block">     Hello World </div> 

And the CSS part:

#block {     background: yellow;     height: 0;     overflow: hidden;     transition: height 300ms linear; }  label {     cursor: pointer; }  #showblock {     display: none; }  #showblock:checked + #block {     height: 40px; } 

The magic is the hidden checkbox and the :checked selector in CSS.

Working jsFiddle Demo.

like image 123
dashtinejad Avatar answered Oct 03 '22 17:10

dashtinejad


You can toggle classes using the classList.toggle() function:

var element = document.getElementById('sidebar'); var trigger = document.getElementById('js-toggle-sidebar'); // or whatever triggers the toggle  trigger.addEventListener('click', function(e) {     e.preventDefault();     element.classList.toggle('sidebar-active'); // or whatever your active class is }); 

That should do everything you need - if you have more than one trigger I'd recommend using document.querySelectorAll(selector) instead.

like image 24
Ian Thomas Avatar answered Oct 03 '22 17:10

Ian Thomas