GroxTheProgrammer GroxTheProgrammer - 3 days ago 7
Javascript Question

How to change background color of a button on click using javascript?

So I have 4 buttons. If I click on one of them, that button's background color should to blue. If that button is not clicked I want the color to remain the same (that color is red) . How do I do it?

Currently it only works for one button. Whenever I click another button, it changes the color of that button, not the one I clicked.

EDIT 1:
Here is my updated code.



function buttonFunction() {
var buttons = new Array("button", "button1", "button2", "button3", "button4");
for (var i in buttons) {
if (onclick = true) {
document.getElementById(buttons[i]).style.backgroundColor = "blue";
}
}
}

<body id="Body">
<!-- Navigation bar setup -->
<header id="Mainheader">
<nav id="Navigation">
<form>
<button type="button" value="submit" class="Button" onclick="buttonFunction()" id="button"><a href="index.html" class="Button-link" >Introduction</a></button>
<button type="button" value="submit" class="Button" onclick="buttonFunction()" id="button"><a href="History-of-astronomy.html" class="Button-link">History of Astronomy</a></button>
<button type="button" value="submit" class="Button" onclick="buttonFunction()" id="button"><a href="Observational-Astronomy.html" class="Button-link" >Observational Astronomy</a></button>
<button type="button" value="submit" class="Button" onclick="buttonFunction()" id="button"><a href="" class="Button-link">More on Astronomy</a></button>
</form>
</nav>
</header>
<!-- Navigation bar setup (complete) -->

A.J A.J
Answer

Pass the button reference in onclick function and change style of it.

function buttonFunction(el) {
  el.style.backgroundColor = "red";
}
<button type="button" value="submit" class="Button" onclick="buttonFunction(this)"><a href="index.html" class="Button-link">Introduction</a>
</button>
<button type="button" value="submit" class="Button" onclick="buttonFunction(this)"><a href="History-of-astronomy.html" class="Button-link">History of Astronomy</a>
</button>
<button type="button" value="submit" class="Button" onclick="buttonFunction(this)"><a href="Observational-Astronomy.html" class="Button-link">Observational Astronomy</a>
</button>
<button type="button" value="submit" class="Button" onclick="buttonFunction(this)"><a href="" class="Button-link">More on Astronomy</a>
</button>

Comments