I am trying to understand how jQuery animations work.
For instance, if I have an a
element with CSS that makes it look like a clickable image and a given with
and height
in CSS, how would I safely animate the width
and height
of this element?
Do I need to animate the values in the CSS class? Or do I need to set a new CSS class with the target values for width
and height
, and let jQuery animate from oldClass
to newClass
?
Or can I simply use the .width()
and .height()
methods of jQuery, regardless of what values are specified in CSS?
What confuses me is: If I tweak the width of an element with jQuery, does this also modify my CSS, or does jQuery / JavaScript simply override the specified values in CSS with something else? I mean: After use jQuery to edit the width, does this width become the new value in the CSS file as well? Can I apply this class to other elements and they will have the new width?
It will overide inline style.
I will now show a version with top, left being animated but you can apply it on almost all CSS properties.
HTML
<span id="test">blablabla</span>
CSS
span{
position:absolute;
display:block;
height:50px;
width:50px;
}
jquery
$('#test').animate({top:'100px',left:'50px'}, 500);
fiddle
I know it's been a long time, but it may help someone looking for the answer anyway. Relying on CSS3 transition property can lead to trouble when wanting to support older browsers.
The requested behaviour of animating between two states (CSS Classes) can fully be accomplished by using jQuery UI, which supports this by extending the switchClass() method. It also supports all the perks of the animate() method, such as duration, easing, callback, etc.
As the official documentation states: '
Similar to native CSS transitions, jQuery UI's class animations provide a smooth transition from one state to another while allowing you to keep all the details about which styles to change in CSS and out of your JavaScript.
You can read all about it here.
jQuery UI can also be compiled to include only the things you need, so you can reduce the size of the library by excluding the features you won't use. Check the available options here.
Hope it helped someone!
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