Rene Pot
Rene Pot

Reputation: 24815

Add multiple lines of CSS with JavaScript of the same property

I'm trying to add multiple lines of CSS for the same property (overruling for multiple browsers) but I only see the last appended.

I see why this happens, but I have no clue on how to fix it. Changing the = into a += didn't work either. How should I change this so they are all appended correctly?

    ribbon.style.background = '-webkit-linear-gradient(left, ' + config.ribbonColorStart + ' 0%, ' + config.ribbonColorEnd + ' 100%)';
    ribbon.style.background = '-moz-linear-gradient(left, ' + config.ribbonColorStart + ' 0%, ' + config.ribbonColorEnd + ' 100%)';
    ribbon.style.background = '-o-linear-gradient(left, ' + config.ribbonColorStart + ' 0%,' + config.ribbonColorEnd + ' 100%)';
    ribbon.style.background = '-ms-linear-gradient(left, ' + config.ribbonColorStart + ' 0%,' + config.ribbonColorEnd + ' 100%)';
    ribbon.style.background = 'linear-gradient(to right, ' + config.ribbonColorStart + ' 0%,' + config.ribbonColorEnd + ' 100%)';

Upvotes: 0

Views: 238

Answers (1)

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324640

You would have to browser-detect it. Something like:

try {
  ribbon.style.backgroundImage = "linear-gradient(...)";
  if( !ribbon.style.backgroundImage || ribbon.style.backgroundImage == "none")
    ribbon.style.backgroundImage = "-webkit-linear-gradient(...)";
  if( !ribbon.style.backgroundImage || ribbon.style.backgroundImage == "none")
    ribbon.style.backgroundImage = "-moz-linear-gradient(...)";
  if( !ribbon.style.backgroundImage || ribbon.style.backgroundImage == "none")
    ribbon.style.backgroundImage = "-o-linear-gradient(...)";
  if( !ribbon.style.backgroundImage || ribbon.style.backgroundImage == "none")
    // gradient not supported, fall back here
}
catch(e) {
  // gradient not supported and browser does't like bad values. Fall back here
}

It should be noted that -ms-linear-gradient has never existed: IE9 didn't support gradients, IE10 fully supports them.

Of course, you could just put the styles in a class and add that class to your element ;)

Upvotes: 1

Related Questions