javascript - Discrepancy between setting width through .animate() and .css() -


i trying reset width of element through jquery (for set width - similar toggle behaviour). experienced interesting issue.

if this, it works, ofcourse without animation:

$(this).parents(".galbox_viewpic_cont:first").css("width",""); 

if this, it not work properly. sets width 100% of entire document.

$(this).parents(".galbox_viewpic_cont:first").animate({"width":""},function(){}); 

i tried specifying auto not work.

$(this).parents(".galbox_viewpic_cont:first").animate({"width":"auto"},function(){}); 

please me out this. want have animation , still want work.

you have animate numeric values, "" , "auto" not numeric jquery or other library cannot interpolate values 1 frame other.

setting width "" via css method clears width property, letting element take width according inherited properties. means "" same "auto". can check in web developer inspector in browser.

alternative 1

if scenario allows it, define starting , ending width , use values animate. should viable option if width of element not depend on width of browser, content or other responsive behavior.

// start $(this).parents(".galbox_viewpic_cont:first").css({"width":"300px"});  // end $(this).parents(".galbox_viewpic_cont:first").animate({"width":"600px"},function(){}); 

alternative 2

you set width via .css method , set css transition element. way altering width in way result in smooth animation.

.galbox_viewpic_cont:first{     -webkit-transition: width 500ms ease-in;     -moz-transition: width 500ms ease-in;     transition: width 500ms ease-in; }  // via js $(this).parents(".galbox_viewpic_cont:first").css({"width":"300px"});  // bit later $(this).parents(".galbox_viewpic_cont:first").css({"width":"600px"}); 

this results in animated transition. however, setting .css "auto" or "" won't animate either.

alternative 3

you automate setting of numeric start value this.

// start var initialwidth = $(this).parents(".galbox_viewpic_cont:first").css('width');  // thing // animate target width  $(this).parents(".galbox_viewpic_cont:first").animate({"width":"600px"},function(){});  // reset animation, set initial width $(this).parents(".galbox_viewpic_cont:first").animate({"width":initialwidth+'px'},function(){}); 

Comments