0

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??
Elvopresla
  • 147
  • 2
  • 14
  • 4
    Don't call the function, just assign the reference: `= hello;` – trincot May 26 '16 at 13:35
  • 1
    don't assign onclick, use .addEventListener('click', hello); instead. I will not create an answer to explain why but you can find out easily. – AxelH May 26 '16 at 13:43

2 Answers2

3

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.

Jeremy J Starcher
  • 23,369
  • 6
  • 54
  • 74
1

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;
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335