Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add vendor prefixed gradients to an element with vanilla JavaScript? [duplicate]

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?

like image 332
Madara's Ghost Avatar asked Nov 01 '22 02:11

Madara's Ghost


1 Answers

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.

like image 50
Benjamin Gruenbaum Avatar answered Nov 14 '22 06:11

Benjamin Gruenbaum