1

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.

1
  • 1
    api.jquery.com/css If you have one or multiple values in JS variables you'll need to concatenate it to the string you set as the value of the rule. Commented Feb 23, 2018 at 14:28

3 Answers 3

2

jQuery Style setting works like this:

anAmazingSlider.css({"background-image": "linear-gradient(to right, #e6e6e6, #e6e6e6 50%, #E74C3C 50%)"});
Sign up to request clarification or add additional context in comments.

Comments

1

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%)`;

1 Comment

Apologies I just meant variables. Your second example is exactly what I was after. Couldn't get the right syntax, but looking at your example, I understand what I need to do.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.