1

Every time I try to add an onclick event to a newly created button, the event seems to get triggered before the button is even pressed. Here is how I've been trying to go about it:

var que = document.createElement("BUTTON");
var text = document.createTextNode("Question1");
que.appendChild(text);
document.body.appendChild(que);
que.setAttribute("onclick", function1());

Each time function1() is run before I even have a chance to press the button. Does anyone have any ideas of why?

2 Answers 2

2

Try this:

que.setAttribute("onclick",function() {function1();})

or this:

que.onclick = function() {function1();}
Sign up to request clarification or add additional context in comments.

Comments

1

It should be que.setAttribute("onclick", "function1()");

See fiddle: https://jsfiddle.net/free_soul/L5s1x1nz/

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.