Markus Hallcyon Markus Hallcyon - 7 months ago 30
HTML Question

Simple if else onclick then do?


  1. How do I make it so if yes button clicked change colour?

  2. Is using .onclick the best option for this?

  3. Am I doing it the optimal way?



Thanks.

html:

<body>
<div id="box"></div>
<button id="yes">yes</button>
<button id="no">no</button>
<script src="js/script.js"></script>
</body>


css:

#box {
width: 200px;
height: 200px;
background-color: red;
}


js:

function Choice () {
var box = document.getElementById("box");
var yes = document.getElementById("yes");
var no = document.getElementById("no");

if (yes.clicked == true) {
box.style.backgroundColor = "red";
} else if (no.clicked == true) {
box.style.backgroundColor = "green";
} else {
box.style.backgroundColor = "purple";
};
};

Choice ();

Answer

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