Ivanka Todorova
Ivanka Todorova

Reputation: 10219

Expand and collapse div

The code for $('.button-up').click(function(){ // } is not being triggered. I cannot find the problem. Here is an online demo for what I'm trying to do.

http://jsfiddle.net/UfnCn/

$('.button-up').click(function(){
    $('.description').animate({height: '80px'}, 400);
    $(this).removeClass('button-up');
    $(this).html('read more');
    $(this).addClass('button-down');
    return false;
});
$('.button-down').click(function(){
    var height = $('.description').css('height','auto').height() + 20; 
    $('.description').css('height','125px'); 
    $('.description').animate({height: height+'px'}, 400);
    $(this).addClass('button-up');
    $(this).html('collapse');
    $(this).removeClass('button-down');
    return false;
});

Upvotes: 0

Views: 91

Answers (2)

Matt Whipple
Matt Whipple

Reputation: 7134

You should be using event delegation and .on. The event handlers are being bound at the time of declaration, and so since the button-up class isn't assigned to the element when the handlers are being attached, nothing is being attached.

You should be able to do something like $("p.overlay").on("click", ".button-up", function(){..});. Attach the handler to any element in the buttons ancestry (document is always a safe bet) that isn't going to change and then use the selector to filter.

Upvotes: 2

Halil Ibrahim
Halil Ibrahim

Reputation: 1369

That is because when you bind the click event with jquery click function there is no element has button-up class. So one way is using jquery on method or using toggle method to swith one state to an other continuously.

Upvotes: 1

Related Questions