Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to toggle animation in jQuery 2.0?

I want to use the jQuery .toggle() event to toggle animation (expand/collapse), The problem is that I'm using jQuery 2.0 where toggle is deprecated in jQuery 1.8 and removed in jQuery 1.9+.

Is there a way to use toggle for this animation?

$("#expand").on("click", function(){
        var el = $("#text"), curHeight = el.height(), 
        autoHeight = el.css('height', 'auto').height();
        el.height(curHeight).animate({height: autoHeight}, 1000);
});

Fiddle Demo

like image 706
Mustapha Aoussar Avatar asked Jan 25 '26 14:01

Mustapha Aoussar


2 Answers

You can toggle a class eg. opened to rapresent the current status of the control and change the code accordingly if the element have or not that class.

Code:

$("#expand").on("click", function () {
    var el = $("#text"),
        curHeight = el.height(),
        autoHeight = el.css('height', 'auto').height();
    if (el.hasClass('opened')) autoHeight="24px"
    el.height(curHeight).animate({
        height: autoHeight
    }, 1000);
    el.toggleClass('opened')
});

Demo: http://jsfiddle.net/9DBsu/

like image 200
Irvin Dominin Avatar answered Jan 28 '26 02:01

Irvin Dominin


You can use use HTML5's data API to accomplish toggling with a click. This just switches the flag at the end of each click, animating to a height dependant on whether or not the div is currently open:

$("#expand").data("open",false).on("click", function(){
    var $this = $(this), flag = $this.data("open");
    var el = $("#text"), curHeight = el.height(), 
    autoHeight = el.css('height', 'auto').height();
    el.height(curHeight).animate({height: flag?24:autoHeight}, 1000);
    $this.data("open",!flag);
});

JSFiddle

like image 27
George Avatar answered Jan 28 '26 02:01

George



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!