Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing background-color of an element in CSS using Javascript [duplicate]

Tags:

javascript

css

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).

like image 432
user1353742 Avatar asked Jan 19 '26 21:01

user1353742


2 Answers

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;
}​
like image 137
iambriansreed Avatar answered Jan 21 '26 11:01

iambriansreed


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');
like image 38
Jamiec Avatar answered Jan 21 '26 09:01

Jamiec