-2

I am a beginner, and I have a problem with my code in JavaScript. Can someone tell me what's wrong here because the code does not work

document.addEventListener('DOMContentLoaded', function() {
  function redf() {
    document.querySelector('h1').style = 'red';
  };
  document.querySelector('#red').onclick = redf();
});
<h1>Hello, World!</h1>
<div>
  <button id="red" style="color: red;">Red</button>
  <button id="blue" style="color: blue;">Blue</button>
  <button id="green" style="color: springgreen;">Green</button>
</div>
j08691
  • 204,283
  • 31
  • 260
  • 272
  • Also you called the redf function rather then just passing it – Raz Luvaton Aug 20 '21 at 15:35
  • Does this answer your question? [onclick function runs automatically](https://stackoverflow.com/questions/14425397/onclick-function-runs-automatically) – Sebastian Simon Aug 20 '21 at 15:39
  • Also, read [What is the difference between a function call and function reference?](/q/15886272/4642212), [In JavaScript, does it make a difference if I call a function with parentheses?](/q/3246928/4642212), and the documentation on [`addEventListener`](//developer.mozilla.org/docs/Web/API/EventTarget/addEventListener) and on [functions](//developer.mozilla.org/docs/Web/JavaScript/Reference/Functions). – Sebastian Simon Aug 20 '21 at 15:41
  • [How do I ask a good question?](https://stackoverflow.com/help/how-to-ask): _"Write a title that summarizes the specific problem"_ + _"**Describe the problem.** "It doesn't work" isn't descriptive enough to help people understand your problem. Instead, tell other readers what the expected behavior should be. Tell other readers what the exact wording of the error message is, and which line of code is producing it."_ – Andreas Aug 20 '21 at 15:43

1 Answers1

4

Two issues with your code.

  1. style= 'red'; should be style.color = 'red';
  2. onclick = redf(); should be onclick = redf;. The () calls the function

document.addEventListener('DOMContentLoaded', function() {
  function redf() {
    document.querySelector('h1').style.color = 'red';
  };
  document.querySelector('#red').onclick = redf;
});
<h1>Hello, World!</h1>
<div>
  <button id="red" style="color: red;">Red</button>
  <button id="blue" style="color: blue;">Blue</button>
  <button id="green" style="color: springgreen;">Green</button>
</div>
j08691
  • 204,283
  • 31
  • 260
  • 272