Kapil Sharma
Kapil Sharma

Reputation: 10417

How to set 'auto' height in JQuery animate

Problem: I've a box(div) with fixed width but unknown (auto) height.

I need to open/close that box using JQuery animate function.

Problem is (commented in code too) on Open event, I need to set auto height, which I'm not able to do. Can someone please help set height to auto?

JSFiddle: http://jsfiddle.net/7m5Qa/ Code also given below:

HTML

<button id="open">open</button>
<button id="close">close</button>
<div id="textselector-body">
    a<br/>
    b<br/>
    c<br/>
</div>​

Java Script

$(document).ready(function(){
    $("#open").click(function(){
        $("#textselector-body").animate({
            height:'100px' //here is problem. I need it 'auto'.
        },2000);
    });
    $("#close").click(function(){
        $("#textselector-body").animate({
            height:'0'
        },2000);
    });
});​

Upvotes: 1

Views: 6885

Answers (4)

Julien Fouilh&#233;
Julien Fouilh&#233;

Reputation: 2658

Have you tried height:'toggle' ? (JQuery.animate())

It'll reverse the transformation anytime you click on the button though, but if you want only one button, it's the solution.

DEMO.

Upvotes: 2

adeneo
adeneo

Reputation: 318252

$(document).ready(function(){
    var H = $("#textselector-body").height();
    $("#open").click(function(){
        $("#textselector-body").animate({
            height:'100px'
        },2000);
    });
    $("#close").click(function(){
        $("#textselector-body").animate({
            height:H
        },2000);
    });
});​

FIDDLE

EDIT:

Not sure I got the question right? If you're just trying to toggle it you can do:

$(function(){
    $("#open, #close").click(function(e){
        $("#textselector-body")[e.target.id=='open'?'slideDown':'slideUp'](2000);
    });
});​

FIDDLE

Upvotes: 1

Kyle
Kyle

Reputation: 67194

You can instead use the .slideUp and .slideDown methods with jQuery:

$("#open").click(function(){
        $("#textselector-body").slideDown('slow')
});

    $("#close").click(function(){
        $("#textselector-body").slideUp('slow')
});

http://jsfiddle.net/Kyle_Sevenoaks/7m5Qa/3/

Upvotes: 1

gabitzish
gabitzish

Reputation: 9691

Have you tried slideDown and slideUp ? :

$(document).ready(function(){
    $("#open").click(function(){
        $("#textselector-body").slideDown(2000);
    });
    $("#close").click(function(){
        $("#textselector-body").slideUp(2000);
    });
});​

jsFiddle: http://jsfiddle.net/7m5Qa/2/

Upvotes: 5

Related Questions