The other day, I found myself with an odd CSS problem that I had not encountered before (or at least not in a really long time); my CSS class properties were being overridden by inline style attributes left over from a jQuery animation. Specifically, jQuery left a "display" property on an element's style attribute which prevented the "display" property of my CSS classes from cascading. As of late, I've been trying hard to push all my formatting into CSS classes, which is why I've probably not run into this issue before. That said, I needed to figure out how to clear the inline style value after the animation had completed. And, as it turns out, jQuery provides a really easy way to do this.
To clear the inline style values of an element, I could have simply cleared the "style" attribute:
myElement.attr( "style", "" );
But that's not really what I wanted to do; I wanted to clear a specific property - not all of the properties that may or may not exist on the element. Reseting the style attribute makes too many assumption about how the element is being used; and, in my particular case, would have further broken the code.
No - what I wanted to do is to remove the inline style for a given property. And with jQuery, this is quite simple - you set the CSS property to the empty string:
myElement.css( "target-property", "" );
This will remove the given property from the inline styles of the element; but, it will leave CSS class properties in place. Pretty awesome!
Here's the code that I demonstrated in the video. The slideToggle() method leaves a "display: block" on the DIV's inline style. This overrides the display property set by the "hidden" class.
I've been using jQuery for like 6 years and I only just found out that you could clear CSS this way. Better late than never!
Want to use code from this post? Check out the license.