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);
});
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')
});
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);
});
You could use .slideToggle()
instead: JSFiddle .
$("#expand").click(function(){
$("div#text").slideToggle("slow");
});
here you go, just remeber a state and the initial height
check=false;
bla=false;
$("#expand").on("click", function(){
if(!check){
check=true;
var el = $("#text"), curHeight = el.height(),
autoHeight = el.css('height', 'auto').height();
bla=curHeight;
el.height(curHeight).animate({height: autoHeight}, 1000);
}else{
var el = $("#text");
el.animate({height: bla}, 1000);
check=false;
}
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.