KittenCodings KittenCodings - 22 days ago 8
CSS Question

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?

Answer

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.