0

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");
});

4
  • are you getting any errors in the console? Commented Mar 19, 2020 at 9:56
  • 3
    You have declared variable clicker three times with const keyword, you need to change the variable names Commented Mar 19, 2020 at 10:03
  • 3 variables of const type are declared with same name which will produce error..Change the names. Commented Mar 19, 2020 at 10:07
  • thanks. yeah that was the problem Commented Mar 27, 2020 at 10:11

1 Answer 1

5

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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.