Home Ask Login Register

Developers Planet

Your answer is one click away!

samil February 2016

how to convert jquery hide/show+animation to javascript?

I want create a left side menu.

I want open and close it with a button.

Currently I use this Jquery code:

    $("#openMenu").click(function() {

    var menu = $("#menu");
    if ($(menu).is(":visible")) {
        $(menu).animate({width: 0}, 1000, function() {$(menu).hide();});
    } else {
        $(menu).show().animate({width: 200}, 1000);           

how can I do it with pure javascript?


Emil S. Jørgensen February 2016

As Gomzy says you can simply use the css display property to hide the menu.

However if you want to animate it you will need something like this:

(function () {
    var menu = {
        //Node is the menu container we wish to manipulate
        node : document.getElementById("menu"),
        //Is the menu open?
        open : false,
        //A handle for our interval
        interval : null,
        //How wide is the open menu?
        openWidth : 200,
        //How many pixels should we open/close with per frame? (speed of transition is determined here)
        pixelPerFrame : 10,
        //Load elements that has the "toggleMenu" class and bind a "onclick" event to them
        init : function () {
            //Self refer so we dont get confused when handling events
            var self = this;
            //Fetching elements
            var togglers = document.getElementsByClassName("toggleMenu");
            //Looping through the elements
            for (var a of togglers) {
                //Bind event
                a.onclick = function (e) {
                    //Here we need the "self" variable
        //Open/close the menu
        toggle : function () {
            //Self refer so we dont get confused when handling events
            var self = this;
            //If the menu doesn't yet have a width modifier, we assume the menu is open
            if (self.node.style.width == "") {
                self.node.style.width = self.openWidth + "px";
                self.open = true;
            //Revert menu direction. Closes when the menu was open and opens if the menu was closed
            self.open = !self.open;
            //Clear any previous menus
            //Setup the interval function
            self.interval = setInterval(function () {
                //If the menu is opening

Post Status

Asked in February 2016
Viewed 1,329 times
Voted 10
Answered 1 times


Leave an answer

Quote of the day: live life