+ 5

How to make a button change the background in JavaScript?

please I've been trying to make this and I can't make the button do that, could you help me?

22nd Dec 2016, 8:04 PM
C.E.
C.E. - avatar
10 Answers
+ 13
<button onclick="function(){ element.style.background='black'; }">click</button> the above code changes background of any element to black by changing property of element
22nd Dec 2016, 8:16 PM
Sandeep Chatterjee
+ 8
I explained that in my code 'Changing Style'. Take a look!
23rd Dec 2016, 6:36 PM
Cezar
Cezar - avatar
+ 5
Thank you both 😁
22nd Dec 2016, 8:20 PM
C.E.
C.E. - avatar
+ 5
You can also change its background when hovered using simple HTML and CSS. First you create the button in HTML: <input type="button" id="button" value="Button"> Then you create the css for normal button: #button {background-color:black;} And finally the CSS for when its hovered: #button:hover {background-color:blue;}
23rd Dec 2016, 1:12 AM
Syvered
Syvered - avatar
+ 3
1)u have to use onclick attribute invoking a function and 2) u shud define the function such a way that it will change ur backgroundcolor if u post ur code i can help u further
22nd Dec 2016, 8:09 PM
Praveen Bsd
Praveen Bsd - avatar
+ 3
michelle add a boolean that's set to true. now in click function check boolean is true or not and if true change background and set it to false
6th Jan 2017, 8:20 PM
Sandeep Chatterjee
+ 2
yes take a look at Cezars code it has controls that set color of elements it is nice it has explanation too of how it works.
24th Dec 2016, 5:51 AM
Sandeep Chatterjee
+ 2
Wow👍
27th Dec 2016, 6:29 PM
Shubham Kumar Sharma
Shubham Kumar Sharma - avatar
+ 2
I want to change my background and lock it
6th Jan 2017, 5:36 PM
Michelle Sanchez
Michelle Sanchez - avatar
+ 1
document.getElementById("").style.background = "yourstyle"
6th Jan 2017, 6:50 PM
Code Freak
Code Freak - avatar