Jim B
Jim B

Reputation: 217

Setting background-image (linear gradient) using jquery variables

I'm looking to set the background-image of a div using a linear gradient which uses a number variable.

I'm not sure how to set the jQuery to split the SetAttribute and add in the variable.

anAmazingSlider.setAttribute("style", "background-image: linear-gradient(to right, #e6e6e6, #e6e6e6 50%, #E74C3C 50%)");

I have a limit variable and need to set the the background % to that limit.

Upvotes: 1

Views: 1495

Answers (3)

Fabrizio Calderan
Fabrizio Calderan

Reputation: 123367

Alternatively you may use CSS variables and define the linear-gradient straight in the CSS like so, using e.g. 0% (or other) as a default value

Codepen demo


CSS

:root {
   --amount: 0%;
}  

.amazingslider {
   background-image: linear-gradient(to right, #e6e6e6, #e6e6e6 var(--amount), #E74C3C var(--amount))
}

and in Javascript just change the amount value (e.g. 50%) via

document.documentElement.style.setProperty("--amount", "50%");

The update of the variable will take effect immediately. A benefit of this approach is obviously to keep off as much CSS as possible from Javascript and let your Javascript code more mantainable.

Upvotes: 1

Mamboleoo
Mamboleoo

Reputation: 519

I don't really know what you mean by 'jQuery variables' ? Your code doesn't seem to rely on jQuery.

You can do it by concatenating the background with your variable like so :

var amount = 50;
anAmazingSlider.setAttribute("style", "background-image: linear-gradient(to right, #e6e6e6, #e6e6e6 " + amount + "%, #E74C3C 50%)");

This code will probably work but I would suggest to use this version instead :

var amount = 50;
anAmazingSlider.style.backgroundImage = "linear-gradient(to right, #e6e6e6, #e6e6e6 " + amount + "%, #E74C3C 50%)";

If you are using the ES6 syntax you can even skip the concatenation by using a Template literal.

var amount = 50;
anAmazingSlider.style.backgroundImage = `linear-gradient(to right, #e6e6e6, #e6e6e6  ${amount}%, #E74C3C 50%)`;

Upvotes: 1

Marvin Fischer
Marvin Fischer

Reputation: 2572

jQuery Style setting works like this:

anAmazingSlider.css({"background-image": "linear-gradient(to right, #e6e6e6, #e6e6e6 50%, #E74C3C 50%)"});

Upvotes: 2

Related Questions