Simple if else onclick then do?
You should use onclick method because the function run once when the page is loaded and no button will be clicked then
So you have to add an even which run every time the user press any key to add the changes to the div background
So the function should be something like this
htmlelement.onclick() = function(){
//Do the changes
}
So your code has to look something like this :
var box = document.getElementById("box");
var yes = document.getElementById("yes");
var no = document.getElementById("no");
yes.onclick = function(){
box.style.backgroundColor = "red";
}
no.onclick = function(){
box.style.backgroundColor = "green";
}
This is meaning that when #yes button is clicked the color of the div is red and when the #no button is clicked the background is green
Here is a Jsfiddle
The preferred modern method is to use addEventListener
either by adding the event listener direct to the element or to a parent of the elements (delegated).
An example, using delegated events, might be
var box = document.getElementById('box');
document.getElementById('buttons').addEventListener('click', function(evt) {
var target = evt.target;
if (target.id === 'yes') {
box.style.backgroundColor = 'red';
} else if (target.id === 'no') {
box.style.backgroundColor = 'green';
} else {
box.style.backgroundColor = 'purple';
}
}, false);
#box {
width: 200px;
height: 200px;
background-color: red;
}
#buttons {
margin-top: 50px;
}
<div id='box'></div>
<div id='buttons'>
<button id='yes'>yes</button>
<button id='no'>no</button>
<p>Click one of the buttons above.</p>
</div>
you call function on page load time but not call on button event, you will need to call function onclick
event, you may add event inline element style or event bining
function Choice(elem) {
var box = document.getElementById("box");
if (elem.id == "no") {
box.style.backgroundColor = "red";
} else if (elem.id == "yes") {
box.style.backgroundColor = "green";
} else {
box.style.backgroundColor = "purple";
};
};
<div id="box">dd</div>
<button id="yes" onclick="Choice(this);">yes</button>
<button id="no" onclick="Choice(this);">no</button>
<button id="other" onclick="Choice(this);">other</button>
or event binding,
window.onload = function() {
var box = document.getElementById("box");
document.getElementById("yes").onclick = function() {
box.style.backgroundColor = "red";
}
document.getElementById("no").onclick = function() {
box.style.backgroundColor = "green";
}
}
<div id="box">dd</div>
<button id="yes">yes</button>
<button id="no">no</button>