'How can I change a button background with javascript?
I have a button having the following CSS background rule applied:
background-image:url('/images/button_1_normal.png');
I would like to change the button's background with JavaScript. I tried the following but it didn't work.
document.getElementById(step2).style.backgroundImage = "url('images/button_1_active.png') no-repeat";
What is the problem? Thank you
Solution 1:[1]
no-repeat is invalid. Only the URL part is a valid value for the background image property.
Either remove that or change your assignment to background:
document.getElementById(step2)
.style.background="url('images/button_1_active.png') no-repeat";
Solution 2:[2]
Check this out. This is a working sample code. Check your image path. My images folder is in the same level as my javascript file.
const actionButton = document.getElementById('action');
actionButton.style.backgroundImage = "url('./images/icon_playback.png')";
<button id="action"></button>
Solution 3:[3]
You set the element id to a variable, add quotes to fix the problem:
document.getElementById('step2').style.backgroundImage = "url('images/button_1_active.png') no-repeat";
JS takes only strings inside quotes as text input.
Solution 4:[4]
Try this:
document.getElementById("step2").style = 'background-image: none; background-color:#3d8ed4;';
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Ishara Amarasekera |
| Solution 3 | Xarber |
| Solution 4 | Xarber |
