masteringtaiwan
masteringtaiwan

Reputation: 335

jQuery animate toggle to exact height

This is working perfectly

$('.closeme').click(function() {
    $('.mybox').animate( { height:"30px" }, { queue:false, duration:500 });
});

BUT

how do I toggle it back?

(if height:"30px" go to the original height size ) ?

this is not proper jquery syntax but just to get the idea :

$('.closeme').click(function() {
    if ! $('.mybox') = height:"30px" { 
        $('.mybox').animate( { height:"30px" }, { queue:false, duration:500 });
    }
    else {
        $('.mybox').animate( { height:"800px" }, { queue:false, duration:500 });
    }
});

Upvotes: 2

Views: 216

Answers (5)

user2189779
user2189779

Reputation:

Please just look at the example. add class in html try it.

$(".closeme").on("click", function () {

    var moveHeight;
    var className = "addProperty";

    if ($('.mybox').hasClass(className)) {

        $('.mybox').removeClass(className);
        moveHeight = "30px";

    }
    else {

        $('.mybox').addClass(className);
        moveHeight = "800px";

    }

    $('.mybox').animate({ height: moveHeight }, 500);

});

Upvotes: 1

AnOldSoul
AnOldSoul

Reputation: 4197

This should do the trick bro : $('.closeme').on('click', function() { var flag = $(this).data('flag'), ani = 30;

if (flag) ani = $('.mybox').data('height');

$('.mybox').animate( { height: ani }, { queue:false, duration:500 });

$(this).data('flag', !flag);
});

Upvotes: 0

patel.milanb
patel.milanb

Reputation: 5992

Working Fiddle: http://jsfiddle.net/patelmilanb1/6AVtH/

$('.closeme').click(function () {
    if ($(this).hasClass("showme")) {
        $('.mybox').animate({
            height: "500px"
        }, {
            queue: false,
            duration: 500
        });
        $(this).removeClass("showme").addClass("closeme").html("close me");
    } else {
        $('.mybox').animate({
            height: "30px"
        }, {
            queue: false,
            duration: 500
        });
        $(this).removeClass("closeme").addClass("showme").html("show me");
    }

});

Upvotes: 0

Turnip
Turnip

Reputation: 36632

$('.closeme').click(function() {
    if ($('.mybox').height() != 30) {
        $('.mybox').animate( { height:"30px" }, { queue:false, duration:500 });
    } else {
        $('.mybox').animate( { height:"800px" }, { queue:false, duration:500 });
    }
});

DEMO

Upvotes: 2

adeneo
adeneo

Reputation: 318182

Just store the original height somewhere, data() seems like a good place

$('.mybox').data('height', $('.mybox').height());

$('.closeme').on('click', function() {
    var flag = $(this).data('flag'),
        ani  = 30;

    if (flag) ani = $('.mybox').data('height');

    $('.mybox').animate( { height: ani }, { queue:false, duration:500 });

    $(this).data('flag', !flag);
});

FIDDLE

Upvotes: 2

Related Questions