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?
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).
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 ...
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.
The classList. toggle() method supports adding and removing CSS classes whether they exist or not in your array with shorter lines of code.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With