简体   繁体   中英

Animate height of div when button is clicked

I'm trying to animate a drop down menu div's height from 0 to 250px, when the menu button is clicked. I tried using jQuery.

This is included in my HTML:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<script src="scripts.js"></script>

The menu button is a span:

<span id="menu_btn" name="menu_button">MENU</span>

And this is the drop down menu:

<div id="menu_dropdown">
    <ul>
        <li><a id="on" href="#">HOME</a></li>
        <!-- more buttons -->
</div>

And this is the jQuery:

$("#menu_btn").toggle(function(){
    $("#menu_dropdown").animate({'height': '250px'}, 100);
}, function(){
    $("#menu_dropdown").animate({'height': '0px'}, 100);
});

However it doesn't work. Why is this?

I think this is what you want:

$("#menu_btn").on('click', function() {
    $("#menu_dropdown").slideToggle(100);
});

Changing the height will probably not work because the it will not prevent the content for being shown. slideToggle() changes the display property, which will work.

See also http://api.jquery.com/slideToggle/

Span is not a button or anchor tag. Also you need to catch a click event first in order to use toggling.

http://jsfiddle.net/3w2tt1wm/

Take alook

Try using anonymous functions in your animate calls instead like below. Then you can explicitly get the element you want to change the height for and do it using jquery's .height(HEIGHT) or .css("height", HEIGHT);

$("#menu_btn").toggle(function(){
    $("#menu_dropdown").animate(function(){$("#menu_dropdown").css("height", "250px");}, 100);
}, function(){
    $("#menu_dropdown").animate(function(){$("#menu_dropdown").css("height", "0px");}, 100);
});

Also, you didn't show it so just make sure the toggle is in a click or mouseover handler function. It won't do you any good otherwise.

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