Jitendra Vyas
Jitendra Vyas

Reputation: 152677

How to give auto height to this jquery toggle (show/hide)

See example here http://jsfiddle.net/jitendravyas/P6vKf/14/

Updated the jsfiddle link

In this example I have 3 different modules for show/hide and all have different height to show and hide the items.

$(function(){
   $(".more-destination").click(function(){
          $(this).parent().prev("ul").animate({
              height: "500px"
           }, 800, function() {});
          $(this).next(".less-destination").toggle();
          $(this).toggle();
   });

   $(".less-destination").click(function(){
         $(this).parent().prev("ul").animate({
             height: "200px"
          }, 800, function() {});
         $(this).prev(".more-destination").toggle();
         $(this).toggle();
   });
});

I want to make the height auto for Min-height (default) AND Max-height ( after open) so i can use the jquery code to any container where I need this effect.

Is it possible?

I want to set min-height only in CSS and for height it should take height upon how many items in the div.

I don't want to give any height or width in javascript. in CSS only

Upvotes: 0

Views: 986

Answers (1)

Christian
Christian

Reputation: 19740

It's possible, just a bit of hackery. You can clone the element, check it's height, then animate to that height. Reverse for minimising the element.

$(".more-destination").click(function(e) {
    e.preventDefault();
    var clone = $(this).parent().prev("ul").clone().appendTo('body').height('auto');
    var height = clone.height();
    clone.remove();

    $(this).parent().prev("ul").animate({
        height: height
    }, 800, function() {});

    $(this).next(".less-destination").toggle();
    $(this).toggle();
});

$(".less-destination").click(function(e) {
    e.preventDefault();
    var clone = $(this).parent().prev("ul").clone().appendTo('body').height('');
    var height = clone.height();
    clone.remove();

    $(this).parent().prev("ul").animate({
        height: height
    }, 800, function() {});

    $(this).prev(".more-destination").toggle();
    $(this).toggle();
});

jsFiddle: http://jsfiddle.net/P6vKf/8/

Upvotes: 1

Related Questions