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
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/
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With