简体   繁体   中英

How do I create a slide out menu?

I've just started and I'm very very new to programming, but i wanna create a slide-out menu bar for a html that I'm testing out my knowledge on,

can anyone help me with this? I've been trying to figure out why my code doesnt work when i click the button:

var isOpened;

function openMenu() {
    $('#sidebar').animate({
        'marginLeft' : "+=248px"
    }, 200);
    $('.mainBody').animate({
        'marginLeft' : "+=248px"
    },200);
    isOpened = true;
};

function closeMenu() {
    $('#sidebar').animate({
        'marginLeft' : "-=248px"
    }, 200);
    $('.mainBody').animate({
        'marginLeft' : "-=248px"
    },200);
    isOpened = false;
};

function animate() {
    if (isOpened === false) {
        $('button').click(function() {
            openMenu();
        });
    } else {
        $('button').click(closeMenu(function(){
            closeMenu();
        }));
    }
};

$(document).ready(animate);

A suggestion not an answer exactly. But can help you.

Instead of the code below from your code snippet,

function animate() {
    if (isOpened === false) {
        $('button').click(function() {
            openMenu();
        });
    } else {
        $('button').click(closeMenu(function(){
            closeMenu();
        }));
    }
};

Do this instead and compare line by line about what did your code do and what this below code will do...

function animate() {
    $('button').click(function() {
        if(isOpened === false) {
            openMenu();
        } else {
            closeMenu();
        }
    });
}

And $(document).ready will execute once and as per your code only one click event is registered. That is handle both close and open in one click event listener.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM