Reputation: 105
How can i change the "background-image" on .btn-1 to the variable "color" that i have on the script? I basically want to change the 3color gradient property of the CSS .btn-1 using JS.
<style>
.btn {
flex: 1 1 auto;
margin: 10px;
padding: 30px;
text-align: center;
text-transform: uppercase;
transition: 0.5s;
background-size: 200% auto;
color: white;
/* text-shadow: 0px 0px 10px rgba(0,0,0,0.2);*/
box-shadow: 0 0 20px #eee;
border-radius: 10px;
}
.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">
<script>
var color = {background-image: linear-gradient(to right, color1 0%, color2 51%, color3 100%)}
</script>
<a name="button" class="btn btn-1">Button Text</a>
</div>
</body>
Upvotes: 3
Views: 81
Reputation: 451
I would recommend you to add a modifier class for btn
class. Modifier class is a part of BEM methodology and it is a sort of helper class which used to change behavior or appearance of the element. Read more about BEM.
After you added your modifier class just add it to your element when you need it.
This approach is better in terms of code cleanness and maintenance. Let me know if you have any questions.
Quick example:
.btn {
flex: 1 1 auto;
margin: 10px;
padding: 30px;
text-align: center;
text-transform: uppercase;
transition: 0.5s;
background-size: 200% auto;
color: white;
/* text-shadow: 0px 0px 10px rgba(0,0,0,0.2);*/
box-shadow: 0 0 20px #eee;
border-radius: 10px;
}
.btn:hover {
background-position: right center;
}
.btn-1 {
background-image: linear-gradient(to right, #f6d365 0%, #fda085 51%, #f6d365 100%);
}
.btn-1--extra {
background-image: linear-gradient(to right, color1 0%, color2 51%, color3 100%);
}
<body>
<div class="container">
<a name="button" id="button" class="btn btn-1">Button Text</a>
</div>
<script>
var button = document.getElementById("button");
button.classList.add("btn-1--extra");
</script>
</body>
Upvotes: 0
Reputation: 17654
var color
needs to be a string, select the element you want using document.querySelector then apply the gradient with element.backgroundImage = color
var color = 'linear - gradient(to right, color1 0 % , color2 51 % , color3 100 % )'
document.querySelector('.btn.btn-1').backgroundImage = color;
.btn {
flex: 1 1 auto;
margin: 10px;
padding: 30px;
text-align: center;
text-transform: uppercase;
transition: 0.5s;
background-size: 200% auto;
color: white;
/* text-shadow: 0px 0px 10px rgba(0,0,0,0.2);*/
box-shadow: 0 0 20px #eee;
border-radius: 10px;
}
.btn:hover {
background-position: right center;
}
.btn-1 {
background-image: linear-gradient(to right, #f6d365 0%, #fda085 51%, #f6d365 100%);
}
<div class="container">
<a name="button" class="btn btn-1">Button Text</a>
</div>
Upvotes: 3