Basically I want to change the background color of an element in CSS using JavaScript at the click of a button.
So far my CSS looks something like this:
div.box {
width:100px;
height:100px;
background-color:#FF2400;
}
It needs to change dynamically to a choice of several colors, just with multiple buttons will do (Each being a different color).
Done: http://jsfiddle.net/iambriansreed/zmtU4/
Updated to be Non-jQuery.
HTML
<div id="box"></div><div id="box"></div>
<button type="button" onclick="button_click('red');">Red</button>
<button type="button" onclick="button_click('blue');">Blue</button>
<button type="button" onclick="button_click('green');">Green</button>
<button type="button" onclick="button_click('yellow');">Yellow</button>
<button type="button" onclick="button_click('purple');">Purple</button>
Pure JavaScript
function button_click(color){
document.getElementById("box").style.backgroundColor=color;
}
The vanilla-javascript way to do this is to get a reference to the element and use style.backgroundColor to change the color:
for example, if the div has an id of myBox you would use
document.getElementById("myBox").style.backgroundColor="#000000"; // change to black
Live example: http://jsfiddle.net/QWgcp/
Incidentally, if you're doing a lot of this kind of manipulation frameworks such as jQuery provide you with some help in writing the code. The same functionality using jQuery would be a bit simpler:
$('#myBox').css('background-color','#000000');
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