The Fix
This is because you are overriding the values of your animation. In CSS inline styles have a higher specificity than linked styles, and the background
attribute is a shorthand that sets both background-image
and background-position
. The styles you're applying via JavaScript are setting new values with higher specificty than your animation keyframes. To fix this, set backgroundImage
rather than background
.
function changeBackground() {
document.body.style.backgroundImage = "linear-gradient(-45deg, #EE7752, #E73C7E, #23A6D5, #23D5AB)";
}
body {
width: 100wh;
height: 90vh;
color: #fff;
background: linear-gradient(-45deg, #EE7752, #E73C7E, #23A6D5, #23D5AB);
background-size: 400% 400%;
-webkit-animation: Gradient 15s ease infinite;
-moz-animation: Gradient 15s ease infinite;
animation: Gradient 15s ease infinite;
}
@-webkit-keyframes Gradient {
0% {
background-position: 0% 50%
}
50% {
background-position: 100% 50%
}
100% {
background-position: 0% 50%
}
}
@-moz-keyframes Gradient {
0% {
background-position: 0% 50%
}
50% {
background-position: 100% 50%
}
100% {
background-position: 0% 50%
}
}
@keyframes Gradient {
0% {
background-position: 0% 50%
}
50% {
background-position: 100% 50%
}
100% {
background-position: 0% 50%
}
}
<a onclick="changeBackground()">Default</a>
<a onclick="clickHandler()">Fire</a> // This will be implemented at a later time.
An Improved Approach
Better yet - use CSS classes to apply the change in styles rather than through JavaScript and avoid the specificity battle altogether. This how CSS is intended to be used.
Also worth mentioning a <button>
is a more appropriate element to use for behavior, as anchors are for sending the user somewhere.
Though, if you're pulling the linear gradient values programmatically this may not be an option.
function setDefault() {
document.querySelector('body').setAttribute('class', '');
};
function clickHandler() {
document.querySelector('body').classList.add('fire');
};
body {
width: 100wh;
height: 90vh;
color: #fff;
background-image: linear-gradient(-45deg, #EE7752, #E73C7E, #23A6D5, #23D5AB);
background-size: 400% 400%;
-webkit-animation: Gradient 15s ease infinite;
-moz-animation: Gradient 15s ease infinite;
animation: Gradient 15s ease infinite;
}
.fire {
background-image: linear-gradient(-45deg, #ff0000, #efefef, #ff0000, #efefef);
}
@-webkit-keyframes Gradient {
0% {
background-position: 0% 50%
}
50% {
background-position: 100% 50%
}
100% {
background-position: 0% 50%
}
}
@-moz-keyframes Gradient {
0% {
background-position: 0% 50%
}
50% {
background-position: 100% 50%
}
100% {
background-position: 0% 50%
}
}
@keyframes Gradient {
0% {
background-position: 0% 50%
}
50% {
background-position: 100% 50%
}
100% {
background-position: 0% 50%
}
}
<button onclick="setDefault()" tyle="button">Default</buttopn>
<button onclick="clickHandler()" tyle="button">Fire</buttopn>