Nico
Nico

Reputation: 161

Toggle height of Div Size

I am searching for a simple way to expand a div to a fixed height. This would be the basic skeleton of my code:

<div class="parent">
    <div class="child">
        Lorem Ipsum
    </div>
    <div class="bar">
        <a class="more" href="#">More</a>
   </div>
</div>

With click on "more", I want the parent div to expand to a height of 400px. With clicking "more" (better would be "less") again, I want the parent div to resize back to it's former height (200px).

Somehow nothing I found on the internet worked. And since I am an absolute greenhorn with jQuery I can't find the mistake... I assume a problem might be the lack of proper element identification since each class is used several times on the website...

Thanks for your help in advance!

Upvotes: 0

Views: 2692

Answers (3)

Kevin Bowersox
Kevin Bowersox

Reputation: 94429

I added a less element to your HTML so that the parent may be collapsed after it is expanded.

HTML

<div class="parent">
    <div class="child">
        Lorem Ipsum
    </div>
    <div class="bar">
        <a class="more" href="#">More</a>
        <a class="less" href="#">Less</a>
   </div>
</div>

CSS

.less{
    display: none;
}

Javascript

var originalHeight = $(".parent").height();
$(".more").click(function(e){
   toggle(this,400, ".less");
   e.preventDefault();
});

$(".less").click(function(e){
   toggle(this,originalHeight, ".more");
   e.preventDefault();
});

function toggle(element, height, toggleClass){
   $(element).parents(".parent").animate({"height":height + "px"},1000);
   $(element).hide();
   $(toggleClass).show();
}

Working Example: http://jsfiddle.net/bsF6V/1/

Upvotes: 0

jmar777
jmar777

Reputation: 39649

With the edition of some CSS:

.parent.large {
    height: 400px;
}

You can use the following JavaScript:

var $parent = $('.parent');

var $link = $('.more').click(function(e) {
    e.preventDefault();
    if ($parent.hasClass('large')) {
        $parent.removeClass('large');
        $link.text('More');
    } else {
        $parent.addClass('large');
        $link.text('Less');
    }
});

Here's a jsfiddle of it in action.

Upvotes: 0

Anoop
Anoop

Reputation: 23208

Try this JSFIDDLE

html:

   <div class="parent">
    <div class="child">
        Lorem Ipsum
    </div>
    <div class="bar">
        <a class="more" href="#">More</a>
   </div>
</div>

js

    var div = $("div.parent");
$("a.more").click(function(){
    if($(this).text().toLowerCase() == "more"){
        div.animate({height:400}, 500);
        $(this).text("Less");   
    }            
    else{
       div.animate({height:200}, 500);
         $(this).text("More");   
    }

});

Upvotes: 2

Related Questions