How to Implement jQuery slideToggle() in Vanilla JavaScript

πŸ™‚ Like
πŸ™‚Like πŸ₯°Love 🧐Watching this 🀨Suspicious πŸ˜’Meh 😑Angry

If you use jQuery for a handful of effects/animations, here’s a quick JavaScript replacement for jQuery slideToggle(). With small changes, it can be adapted to replace fadeToggle() or simply toggle().


<a href="#" id="toggle">Slide Toggle</a>

<div id="toggleMe">
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
    <p>Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>


let container = document.getElementById('toggleMe');

document.getElementById('toggle').addEventListener('click', function (event) {

    if (!container.classList.contains('active')) {
        container.classList.add('active'); = 'auto';

        let height = container.clientHeight + "px"; = '0px';

        setTimeout(function () {
   = height;
        }, 0);
    } else { = '0px';

        container.addEventListener('transitionend', function () {
        }, {
            once: true


#toggleMe {
    transition: height .25s ease;
    overflow: hidden;
#toggleMe:not(.active) {
    display: none;

See a JSFiddle demo.

Find more JavaScript tutorials, code snippets and samples here or more jQuery tutorials, code snippets and samples here.

Added by Ciprian on Thursday, May 24, 2018 in JavaScript

Unlimited Automated Page Speed Monitoring & Tracking.
Use SpeedFactor to track your website. It’s simple and reliable.
See how real people experience the speed of your website. Then find (and fix) your web performance problems.
Get Started

Related Articles

%d bloggers like this:
Privacy Policy