YUI3 FF retrieving selected option and its background-color property

89 Views Asked by At

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.

http://jsfiddle.net/9sy02756/6/

1

There are 1 best solutions below

1
François-Xavier Aeberhard On

In your code, when you do this.one('option:checked').getStyle('backgroundColor'), YUI uses the window.getComputedStyle method.

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>'s mouseenter event, and apply it during change. But mouseenter on <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.

YUI().use('node', 'selector-css3', function(Y) {
  var lastColor;

  function set_color(e) {
    this.setStyle('backgroundColor', lastColor || this.one('option:checked').getStyle('backgroundColor'));
  };

  Y.on(['available', 'change'], set_color, '#id_linkcolor');

  // For firefox, store computed color before default select blue is applied
  Y.on("mouseover", function(e) {
    lastColor = e.target.getStyle('backgroundColor');
  }, '#id_linkcolor option');
});

http://jsfiddle.net/fxaeberhard/hy3okdph/