I have this, it worked before if I set the background and put the linear gradient inside the data-src, but when I changed it to this so that it would support more browsers, it isn't working anymore. The background gets set to an image but the gradient isn't showing up. The message that gets sent to the console is
linear-gradient(to top, rgba(2, 0, 36, .8) 0%, rgba(0, 0, 0, 0) 100%), url( '/static/images/mountain.jpg');
var url = "url( '" + slide.dataset.src + "')";
slide.style.backgroundImage = url;
if (slide.dataset.type == 'linear') {
var direction = slide.dataset.lindir;
var linstart = slide.dataset.linstart;
var linend = slide.dataset.linend;
var gradient = "linear-gradient(" + direction + ", " + linstart + ", " + linend + ")";
if (!(url == null)) {
gradient += (", " + url);
}
gradient += (";");
console.log(gradient);
slide.style.background = "-moz-" + gradient;
slide.style.background = "-webkit-" + gradient;
slide.style.background = gradient;
}
<div class="content category cursor-hand has-text-centered load" data-type="linear" data-lindir="to top" data-linstart="rgba(2, 0, 36, .8) 0%" data-linend="rgba(0, 0, 0, 0) 100%" data-src="{{ category.url }}">
The root problem is that you don't need the semicolon you are adding because you are setting the style in JavaScript, not adding a style to a stylesheet. I've commented that out below, and you can see that it works.
As others have pointed out, you are also doing your vendor prefixes incorrectly. See Setting vendor-prefixed CSS using javascript for more info on that topic.
Note, though, that support for multiple CSS backgrounds goes back to IE 9, so you probably don't need prefixes at all.
One thing to note is that since you are not setting any other background properties in your JS besides the background-image it would probably be best to use style.backgroundImage throughout instead of switching to style.background. This will let you control the other properties included in the background shorthand in your stylesheet.
var slide = document.querySelector('.slide');
var url = "url( '" + slide.dataset.src + "')";
slide.style.backgroundImage = url;
if (slide.dataset.type == 'linear') {
var direction = slide.dataset.lindir;
var linstart = slide.dataset.linstart;
var linend = slide.dataset.linend;
var gradient = "linear-gradient(" + direction + ", " + linstart + ", " + linend + ")";
if (!(url == null)) {
gradient += (", " + url);
}
//gradient += (";");
console.log(gradient);
slide.style.MozBackground = gradient;
slide.style.WebkitBackground = gradient;
slide.style.background = gradient;
}
.slide {
width: 300px;
height: 300px;
}
<div class="slide content category cursor-hand has-text-centered load" data-type="linear" data-lindir="to top" data-linstart="rgba(2, 0, 36, .8) 0%" data-linend="rgba(0, 0, 0, 0) 100%" data-src="{{ category.url }}"></div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With