Reputation: 23
I am new to javascript. I have a problem but I don't know what it could be. Iam supposed to link my javascript to my html. There are three buttons that should turn the text to a diffrent color on clicking. But it is not working.
// this is the red button
const header = document.querySelector("#header");
const clicker = document.querySelector(".clicker-red");
clicker.addEventListener("click", () => {
header.style.backgroundColor = "red";
header.classList.add("large");
});
// this is the green button
const clicker = document.querySelector(".clicker-green");
clicker.addEventListener("click", () => {
header.style.backgroundColor = "green";
header.classList.add("large");
});
// this is the purple button
const clicker = document.querySelector(".clicker-pruple");
clicker.addEventListener("click", () => {
header.style.backgroundColor = "purple";
header.classList.add("large");
});
Upvotes: 0
Views: 69
Reputation: 2432
As I have said in the comments, You cannot declare variable with same name in the same Lexical Environment (i.e, in the same block).
So, you need to change the variable name.
Here is the working example.
const header = document.querySelector("#header");
const clickerRed = document.querySelector(".clicker-red");
clickerRed.addEventListener("click", () => {
header.style.backgroundColor = "red";
});
// //this is the green button
const clickerGreen = document.querySelector(".clicker-green");
clickerGreen.addEventListener("click", () => {
header.style.backgroundColor = "green";
});
// // this is the purple button
const clickerPurple = document.querySelector(".clicker-purple");
clickerPurple.addEventListener("click", () => {
header.style.backgroundColor = "purple";
});
<div id="header">
Header</div>
<button class="clicker-red" type="button">Red</button>
<button class="clicker-green" type="button">Green</button>
<button class="clicker-purple" type="button">Purple</button>
Upvotes: 5