5

I want to programmatically add a gradient background to an element.

With proper CSS that would be something like this

background: -moz-linear-gradient(top, #000000 0%, #ffffff 100%); /* FF3.6+ */
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#000000), color-stop(100%,#ffffff)); /* Chrome,Safari4+ */
background: -webkit-linear-gradient(top, #000000 0%,#ffffff 100%); /* Chrome10+,Safari5.1+ */
background: -o-linear-gradient(top, #000000 0%,#ffffff 100%); /* Opera 11.10+ */
background: -ms-linear-gradient(top, #000000 0%,#ffffff 100%); /* IE10+ */
background: linear-gradient(to bottom, #000000 0%,#ffffff 100%); /* W3C */

Now, I want to do it with JavaScript. So I thought up of something like this:

gradientList.forEach(gradient => el.style.background = gradient)

However, that won't work. The background property will be overridden each time, and only the last gradient on the list will be applied.

With most other properties, the property name is different between vendors, with the case of linear-gradient however, they're all background.

Now, I know I can just add a classname to the element and append a style node to document.head (which is what I'm doing right now), but it's pretty hackish, and I want a better DOM way of doing things.

In short, how do I add vendor prefixed gradient to a DOM element with vanilla JavaScript?

Madara's Ghost
  • 172,118
  • 50
  • 264
  • 308
  • 1
    Off my head, I'd just go through a class. – Florian Margaine Jun 15 '15 at 13:56
  • I'd go through a class as well. Otherwise you'd have to loop through all DOM objects, just to check if they have a background, then prefix it. You could select it by a class, but then you might as well add the prefixes into the class. – ndugger Jun 15 '15 at 13:57
  • 1
    I was about to post [this](http://jsfiddle.net/7ntzxhqm/1/) before it got marked as dupe :) The browser prefix identification script is from [Lea Verou's site](http://lea.verou.me/2009/02/find-the-vendor-prefix-of-the-current-browser/). – Harry Jun 15 '15 at 14:11
  • Or you can set the styles inline via the `style` attribute, like [in this bin](http://jsbin.com/fezuco/edit?js,output). I added a bit more explanation by answering the [other question here](http://stackoverflow.com/a/30847841/1446845). – Aurelio Jun 15 '15 at 14:35
  • 1
    @Nobita that definitely works. I think it's the best way so far. – Madara's Ghost Jun 15 '15 at 14:43

1 Answers1

2

Assuming you don't want to go through a library the easy way would be to detect the browser and then do:

el.style.background = browserPrefix + gradient;

In general, the prefix-free library also normalizes a bunch of other stuff for gradients so I warmly recommend it.

Benjamin Gruenbaum
  • 270,886
  • 87
  • 504
  • 504