I am learning Javascript and I'm trying to clean up my code. The code is pretty simple: it simply changes the color of some text by clicking some different buttons. When you click the red button the text turns red, the blue button the text turns blue, etc. Here is the code:
HTML:
<h1 id="title">Change my color!</h1>
<button id="btn" onclick="colorRed()">Red</button>
<button id="btn" onclick="colorGreen()">Green</button>
<button id="btn" onclick="colorBlue()">Blue</button>
<button id="btn" onclick="colorBlack()">Black</button>
Javascript:
var title = document.getElementById("title");
function colorRed() {
title.style.color = "red";
}
function colorGreen() {
title.style.color = "green";
}
function colorBlue() {
title.style.color = "blue";
}
function colorBlack() {
title.style.color = "black";
}
This code works. My question is how do I clean up my Javascript; in a case where I would've had 20 buttons, coding 20 different functions would obviously not be the way to go.
I did try the following for every single color, but that didn't work:
Javascript:
var title = document.getElementById("title");
var btn = document.getElementById("btn");
function changeColor() {
if(btn.innerHTML == "Red") {
title.style.color = "red";
} else if ...
}
I think it goes wrong when I try to identify which button has been clicked by seeing if their inner HTML is equal to a certain color, but I'm not sure how to fix that. Help would be much appreciated!
EDIT: My question isn't a duplicate of Change an element's background color when clicking a different element as the code I wrote works already, and I just want to learn how to clean it up.