Reputation: 4593
Assume you have a list item, <li id="foo">
which you want to fade from one color to another when moused over, and that you are using jQuery. This is fairly easy:
$('li#foo').bind('mouseenter' , function(e) {
$(this).animate({backgroundColor: '#F00'} , 300);
});
However, what if you wanted to get the resulting color or other style rules from a class defined in CSS without also declaring them in JavaScript? It seems there's no way to learn style information from CSS rules without having an example of the rule already in the document, which would require you to animate the <li>
to the target appearance, then in the animation-finished callback, set the class which leads to redundant style declarations and can foul up your CSS at "runtime".
Sorry if this question's unclear: It doesn't occur in the context of any specific project, I'm just curious how you'd go about this. Also, I know CSS3 hypothetically includes support for such transitions but using CSS for dynamic behavior like this seems such an ugly hack.
Upvotes: 0
Views: 72
Reputation: 6257
I've played around a little with Calvin's idea, and this is what I got:
Assuming the following CSS:
#somediv .bar em {
color: #080;
}
You can create the elements virtually and get the style information that way:
$('<div id="somediv"><span class="bar"><em>')
.find('em').css('color')
Upvotes: 0
Reputation: 32726
You should be able to simply do:
$(this).css('background-color')
If you want to get the color AFTER its been updated, add it to the callback, like:
$('li#foo').bind('mouseenter' , function(e) {
$(this).animate({backgroundColor: '#F00'} , 300,function(){
alert($(this).css('background-color'));
});
});
You can then save that to a var, or do whatever you wanted to do with it. You could also change your "bind" to "live" and it will update automatically each time its run:
$(selector).live(event,function(){
alert($(this).css('background-color'));
});
As a side note, you shouldnt do li#foo :) just do #foo speeds up your selection time and its unnecessary as there is only 1 element with that ID.
Upvotes: 0
Reputation: 91734
I'm pretty sure javascript can't read your style-sheet.
If you want a certain property from the style-sheet that does not occur anywhere on the page, you will have to add an invisible element that has that style applied, either at page-load time in the html or with javascript whenever you want.
It does seem a bit theoretical though, instead of defining styles in your style-sheet that you are not using, you might as well declare the appropriate variable directly in javascript.
Upvotes: 1