Dynamically changing the CSS of a button, using JavaScript, and custom variables
Update:
The other answer was actually correct the actual problem was the spaces before the %
sign. I cleaned it up when I manually moved the code over:
var color = 'linear-gradient(to right, ' + color1 + ' 0 % , ' + color2 + ' 51 % ,' + color3 + ' 100 % )';
Should be:
var color = 'linear-gradient(to right, ' + color1 + ' 0% , ' + color2 + ' 51% ,' + color3 + ' 100% )';
Here's the CodePen https://codepen.io/anon/pen/bzZmrm - note you can use the CSS and JS boxes to input your respective code.
This line here is the culprit:
var color = 'linear - gradient(to right, ' + color1 + ' 0 % , ' + color2 + ' 51 % ,' + color3 + ' 100 % )';
As pointed out earlier, there should not be a space between linear - gradient
, instead it should be linear-gradient
. The other issue is that there are also spaces in the percentages of the steps. 0 %
should be 0%
.
If you remove the spaces, you will get the intended result. However, to avoid problems that stem from dynamically building strings with the concatenation operator, I invite you to take a look at template literals.
Here is the same statement using template literals. I personally find that it is less confusing to read.
var color = `linear-gradient(to right, ${color1} 0%, ${color2} 51% , ${color3} 100%)`;
Finally, here's a CodePen applying all that I've said, in addition to using a function to build the background-image
value. Hopefully, it will give you a direction to go towards.