I'm trying to set the background-color of a Select element to the background-color of it's selected Option like so:
YUI().use('selector-css3', 'node', function(Y) {
function set_color( e ) {
this.setStyle('backgroundColor',this.one('option:checked').getStyle('backgroundColor'));
};
Y.on(['available','change'], set_color, '#id_linkcolor');
});
Strangely this works perfectly in Chrome. In FF however it seems to always revert to a specific color. Even more weirdly, this:
this.setStyle('backgroundColor',this.get('options').item(3).getStyle('backgroundColor');
does seem to work. But when I use the selectedIndex to retrieve the selected option it doesn't work anymore.
Check it out here: http://jsfiddle.net/9sy02756/4/
Thanks!
UPDATE
I decided to approach this differently like this:
function set_color( e ) {
this.set('className','');
this.addClass( 'linkcolor_'+this.one('option:checked').get('value') );
};
This way the parent SELECT element just gets assigned the same class as the selected child OPTION and css takes care of the rest. Probably a cleaner solution anyway.
In your code, when you do
this.one('option:checked').getStyle('backgroundColor'), YUI uses thewindow.getComputedStylemethod.In Firefox, getting the background color on an
<option>returns the hover color, which turns out to be a very nice blue. And it will remains that way until you open the select again.The only way around this is to store the color during
<option>'smouseenterevent, and apply it duringchange. Butmouseenteron<option>are only triggered in firefox, not chrome nor IE.In the end you will need a mix of both approaches to get it right. So the question is answered, the mystery solved, but the alternative approach you proposed in the edit is way simpler.
http://jsfiddle.net/fxaeberhard/hy3okdph/