Reputation: 1860
I was trying to reset the width of an element through JQuery (for which i set the width already - Similar to Toggle behaviour). I experienced an interesting issue.
If I do this, IT WORKS, ofcourse without any animation:
$(this).parents(".galbox_viewpic_cont:first").css("width","");
If I do this, IT DOES NOT WORK PROPERLY. It sets the width to 100% of the entire document.
$(this).parents(".galbox_viewpic_cont:first").animate({"width":""},function(){});
I also tried specifying auto but it also does not work.
$(this).parents(".galbox_viewpic_cont:first").animate({"width":"auto"},function(){});
Please help me out with this. I want to have an animation and still want it to work.
Upvotes: 1
Views: 27
Reputation: 6196
You have to animate to numeric values, "" and "auto" are not numeric so jquery or any other library cannot interpolate the values from one frame to the other.
Setting the width to "" via the css method actually clears the width property, letting the element take the width according to the inherited properties. Usually this means "" is the same as "auto". You can check this in the web developer inspector in the browser.
Alternative 1
If your scenario allows it, define a starting and ending width and use those values to animate. This should be a viable option if the width of the element does not depend on the width of the browser, its content or any 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 could also set the width via the .css method and set a css transition to the element. This way altering the width in any way will result in a smooth animation.
.galbox_viewpic_cont:first{
-webkit-transition: width 500ms ease-in;
-moz-transition: width 500ms ease-in;
transition: width 500ms ease-in;
}
// then via js
$(this).parents(".galbox_viewpic_cont:first").css({"width":"300px"});
// a bit later
$(this).parents(".galbox_viewpic_cont:first").css({"width":"600px"});
This results in an animated transition. However, setting .css to "auto" or "" won't animate it either.
Alternative 3
You could then automate the setting of the numeric start value like this.
// start
var initialWidth = $(this).parents(".galbox_viewpic_cont:first").css('width');
// then do your thing
// then animate to a target width
$(this).parents(".galbox_viewpic_cont:first").animate({"width":"600px"},function(){});
// then to reset the animation, set it to the initial width
$(this).parents(".galbox_viewpic_cont:first").animate({"width":initialWidth+'px'},function(){});
Upvotes: 1