I have one button that gets style from .btn-1.:
<a id="button1" class="btn btn-1">Hover me</a><br>
In the script, I have three variables, combining them in one string to create the gradient color on the button:
var color1 = "#fdceaa";
var color2 = "#FFFFFF";
var color3 = "#FFFFFF";
var color = 'linear - gradient(to right, ' + color1 + ' 0 % , ' + color2 + ' 51 % ,' + color3 + ' 100 % )'
And then I want to apply this "color" variable to the background-image, so that the button have a different gradient color.
I tried two different ways, one with document.querySelector and one with jQuery $('.btn.btn-1').css, but none of which worked (it didn't change the color of the button):
document.querySelector('.btn.btn-1')['background-image'] = color;
$('.btn.btn-1').css('background-image', color);
The console had no errors...
Full Code:
<style>
body {
font-family: 'Montserrat', sans-serif;
margin: 0;
}
.container {
display: flex;
justify-content: center;
align-items: center;
align-content: center;
flex-wrap: wrap;
width: 100%;
margin: 0 auto;
height: 100%;
}
.btn {
flex: 1 1 auto;
margin: 10;
padding: 20px;
text-align: center;
transition: 0.5s;
background-size: 200% auto;
color: white;
box-shadow: 0 0 20px #eee;
border-radius: 1000px;
}
.btn:hover {
background-position: right center;
}
.btn-1 {
background-image: linear-gradient(to right, #f6d365 0%, #fda085 51%, #f6d365 100%);
}
</style>
<body>
<div class="container">
<a id="button1" class="btn btn-1">Hover me</a><br>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
var color1 = "#fdceaa";
var color2 = "#FFFFFF";
var color3 = "#FFFFFF";
var color = 'linear - gradient(to right, ' + color1 + ' 0 % , ' + color2 + ' 51 % ,' + color3 + ' 100 % )'
document.querySelector('.btn.btn-1')['background-image'] = color;
$('.btn.btn-1').css('background-image', "red");
</script>
</div>
</body>
https://codepen.io/anon/pen/VgRxoK?editors=1010
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.
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