Convert Jquery slidetoggle code to Javascript

Well this is not converting the jQuery code to javascript, but rather doing it in plain javascript. It can be achieved in different ways. Here are two that comes to my mind:

HTML:

<button id="mbtn" onclick="slideToggle()">SlideToggle</button>
<div id="mdiv">Some context</div>

1. Using javascript’s setInterval :
Having a boolean value to keep track of whether we need to slideUp or slideDown (toggle) and using setInterval to increase/decrease the height.

jsfiddle DEMO

Javascript:

var slideOpen = true;
var heightChecked = false;
var initHeight = 0;
var intval = null;

function slideToggle() {
    window.clearInterval(intval);
    var mdiv = document.getElementById('mdiv');
    if(!heightChecked) {
        initHeight = mdiv.offsetHeight;
        heightChecked = true;
    }
    if(slideOpen) {
        var h = initHeight;
        slideOpen = false;
        intval = setInterval(function(){
            h--;
            mdiv.style.height = h + 'px';
            if(h <= 0)
                window.clearInterval(intval);
            }, 1
        );
    }
    else {
        var h = 0;
        slideOpen = true;
        intval = setInterval(function(){
            h++;
            mdiv.style.height = h + 'px';
            if(h >= initHeight)
                window.clearInterval(intval);
            }, 1
        );
    }
}

2. Using CSS3 transition:
Getting help from CSS3 transition to go along with javascript which will make it a lot easier to achieve the slide effect. Then we’ll only need to change the height in javascript and the rest is done.

jsfiddle DEMO

CSS:

#mdiv {
    /* other styles */
    -webkit-transition: all 1s ease-in-out;
    transition: all 1s ease-in-out;
}

Javascript:

var slideOpen = true;
var heightChecked = false;
var initHeight = 0;

function slideToggle() {
    var mdiv = document.getElementById('mdiv');
    if(!heightChecked) {
        initHeight = mdiv.offsetHeight;
        heightChecked = true;
    }
    if(slideOpen) {
        slideOpen = false;
        mdiv.style.height="0px";
    }
    else {
        slideOpen = true;
        mdiv.style.height = initHeight + 'px';
    }
}

EDIT:
If we want the starting height to be 0, then we’ll need a few changes:

var slideOpen = false;
//var heightChecked = false;
var initHeight = 120; //height of the element when it's fully open

And we need to comment this bit out:

/*
if(!heightChecked) {
    initHeight = mdiv.offsetHeight;
    heightChecked = true;
}
*/

jsfiddle DEMO

EDIT #2
As Sandro pointed out, context wasn’t actually getting hidden so updated the fiddles and added overflow-y: hidden; and changed the text color for visibility.
Also changed open to slideOpen since open is sort of a reserved word.

Leave a Comment