Slide Up / Down [Pure JS]

An implementation of revealing an element using CSS3 to have it slide down to reveal and slide up to hide.

by Cam Gould

HTML

<div class="toggle-content">Show / Hide</div>

<hr />

<div class="hidden-content slide-up">
   Ribeye fatback tongue spare ribs cow doner salami short ribs pork chop pork loin. Salami andouille kielbasa hamburger. Bresaola hamburger capicola ball tip, brisket tri-tip meatloaf flank pork loin ribeye spare ribs. Turkey ground round pork chop, leberkas short ribs jowl doner tongue pork loin.    
</div>

<hr />

<div>
    Some content here
</div>

CSS

.slide-up, .slide-down {
    max-height: 0;            
    overflow-y: hidden;
    -webkit-transition: max-height 0.5s ease-in-out;
    -moz-transition: max-height 0.5s ease-in-out;
    -o-transition: max-height 0.5s ease-in-out;
    transition: max-height 0.5s ease-in-out;
}

.slide-down {            
    max-height: 10em;
}

JavaScript

(function(document) {
    "use strict";
    
    var hidden_el  = document.getElementsByClassName("hidden-content"),
        control_el = document.getElementsByClassName("toggle-content");
        
    if (hidden_el.length < 1 || control_el.length < 1) {
        return;
    }

    // Get the elements
    hidden_el  = hidden_el[0];
    control_el = control_el[0];

    control_el.onclick = function() {
        var element_classes = (" "+hidden_el.className+" ").replace(/[\n\t\r]/g, " "),
            remove_class    = "slide-down",
            add_class       = "slide-up",
            is_showing      = element_classes.indexOf(" "+remove_class+" ") > -1;

        if ( ! is_showing) {
            // Switch variable values
            remove_class = [add_class, add_class = remove_class][0];
        }

        // Remove the previous class (if present) and add the new class
        hidden_el.className = (element_classes.replace(" "+remove_class+" ", "") + " "+add_class+" ").trim();

        return false;
    };
})(document);