Yammi
Yammi

Reputation: 735

jQuery - Animate height not working as expected

Can't seem to get this to work, any ideas?

http://jsfiddle.net/U92bM/

JavaScript:

$('.articleSlide').each(function () {
    var current = $(this);
    current.attr("box_h", current.height());
});

$(".articleSlide").css("height", "100px");

$(".showHide").html('<a href="#">More</a>');

$('.showHide a').click(function() {
    var open_height = $(".articleSlide").attr("box_h") + "px";
    $(this).closest("articleSlide").animate({"height": open_height}, {duration: "slow" });  
});

HTML:

<div class="articleSlide">
    <!-- lots of text -->
</div>

<div class="showHide"></div>

Upvotes: 0

Views: 1821

Answers (3)

Bene
Bene

Reputation: 1905

Try binding your click event with .live() method since you're adding the anchor to the DOM dynamicly. Also, you dont need to add an attribute "box_h" to each '.articleSlide' giving them values of the 'current.height()'. Just use the height on time. Pretty much like this:

$('.showHide a').live('click', function() {
    var open_height = $(".articleSlide").height() + "px";
    $(this).closest("articleSlide").animate({"height": open_height}, {duration: "slow" });  
});

And what about:

$('.showHide a').click(function(e) {
    var open_height = $(e.target).height() + "px";
    $(this).closest("articleSlide").animate({"height": open_height}, {duration: "slow" });  
});

Use the "e.target" to make sure you get the right link's height. I assume you tested to make sure the .click() worked fine. You could also test the same animation but removing the "px" string since I tried this once and it worked. And you can remove entirely the ".each()" function.

Upvotes: 0

Felix Kling
Felix Kling

Reputation: 816302

You got the relationship between the elements wrong. closest searches for the closest ancestor but the articleSlide div is not an ancestor of the link. It is a sibling of its parent. This would work:

$(this).parent().prev().animate(...);

http://jsfiddle.net/U92bM/7/

Upvotes: 1

Naftali
Naftali

Reputation: 146302

try this instead:

$('.articleSlide').each(function() {
    var current = $(this);
    current.attr("box_h", current.height());
});

$(".articleSlide").css("height", "100px");

$(".showHide").html('<a href="#">More</a>');

$('.showHide a').click(function() {
    var open_height = $(".articleSlide").attr("box_h") + "px";
    $(this).parent().parent().children('.articleSlide')
        .animate({"height": open_height}, "slow" );
});

http://jsfiddle.net/maniator/U92bM/5/

You have to goto the anchor tag's grandparent in order to find the element you want to manipulate

works like a charm ^_^

Upvotes: 1

Related Questions