Domanda

I have a div with height:0px and I want it to increase height to 300px when I click on a button.

When I click on the button again, I want it to get height of 0px again.

CSS

nav{
    height:0px;
    overflow:hidden;
    opacity:0;
}

JS

    $("#hamburger").click(function(){
            $('nav').stop().animate({ height: 300, opacity: 1 }, 'slow');
        },function(){
            $('nav').stop().animate({ height: 0, opacity: 0 }, 'slow');
    });

If I only use:

$("#hamburger").click(function(){
        $('nav').stop().animate({ height: 300, opacity: 1 }, 'slow');
});

the animation works. as soon as I add the other line, it doesn't. I also tried using the toggle() function, but the result was that as soon as I load my page, the second part of the toggle function (which is height:0, opacity:0) loaded by itself.

here is a link to my website

Any ideas? Thanks

EDIT

I forgot to say that i am making my website responsive, and that this js code only concerns the mobile version, so to see the result, you should set your browser width to 480px or less

È stato utile?

Soluzione

You're trying to call both functions at the same time. One function wants to increase the height of the div, and the other wants to decrease the height of the div.

Try something like this:

$("#hamburger").click(function(){
    var maxHeight = 300;

    if(+$('nav').height() < maxHeight) {

        $('nav').stop().animate({ height: 300, opacity: 1 }, 'slow');

    } else if (+$('nav').height() === maxHeight) {

        $('nav').stop().animate({ height: 0, opacity: 0 }, 'slow');

    }
});

To make it even shorter, you could do:

$("#hamburger").click(function(){
    var maxHeight = 300,
        nav = $('nav');

        nav.stop().animate({ height: +nav.height() < maxHeight ? 300 : 0, opacity: +nav.css('opacity') === 1 ? 0 : 1 }, 'slow');
});

By the way, the random + signs typecast any strings into numbers, just in case.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top