'Javascript function call with onclick [duplicate]

I have a problem with this code, when I click the button it should do the function "hello" and open an alert but it doesn't work.

function hello(){
  alert("hi");
  }

document.getElementById("one").onclick = hello();
<button id="one">Click me </button>

I know that I could simply do like this

button onclick="hello()";
but I need it to work with the javascript version. Basically my question is: Is there a way to open the function "hello" when I click the button without putting the onclick in the button tag??


Solution 1:[1]

This is a common problem, but I couldn't find a canonical answer to link you to.

Your issue this line:

document.getElementById("one").onclick = hello()

which executes the function hello then assigns the return value of that function to onclick.

You really want this:

document.getElementById("one").onclick = hello;

which assigns a function reference to the onclick property.

That said, the use of onclick is rather out-dated and use of addEventListener is recommended for a number of reasons.

Solution 2:[2]

You have to assign a function to the onclick property.

You are immediately calling the hello function and assigning its return value (which is undefined).

Don't put () after the function name.

document.getElementById("one").onclick = hello;

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jeremy J Starcher
Solution 2 Quentin