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??

2
  • 4
    Don't call the function, just assign the reference: = hello; Commented May 26, 2016 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. Commented May 26, 2016 at 13:43

2 Answers 2

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.

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

1 Comment

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;

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.