getButterfly
Resume

NAVIGATION

ATTRIBUTION

getButterfly
Dublin, Ireland

All Content Copyright ©2018
getButterfly

How to Implement jQuery slideToggle() in Vanilla JavaScript

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().

HTML

<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>
</div>

JavaScript

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

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

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

        var height = container.clientHeight + "px";

        container.style.height = '0px';

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

        container.addEventListener('transitionend', function () {
            container.classList.remove('active');
        }, {
            once: true
        });
    }
});

CSS

body {
    font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif, "Segoe UI Symbol", "Apple Color Emoji", "Segoe UI Emoji";
    font-size: 14px;
    line-height: 1.5;
    color: #24292e;
    background-color: #fff;
}

#toggleMe {
    -webkit-transition: height .25s ease;
         -o-transition: height .25s ease;
            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.


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.


My Battle Tested Recommendations

Jetpack
Dreamhost
WordPress.com
CodeCanyon
SEMrush

Disclaimer: These recommendations contain affiliate links.