1

Can someone explain me like i'm five why is it executing the function without the click event. And how to fix it. Thanks.

function test(){
    alert("works");
}

function createButton(name,location,id,funX){
    var button = document.createElement("input");
    button.type = "submit";
    button.name = name;
    button.id = id;
    button.onclick = funX;
    var placeHolder = document.getElementById(location);
    placeHolder.appendChild(button);
};



window.onload = function () {
    createButton("Submit","content","submitEnd",test());
};

http://jsfiddle.net/mabui91/yLoty39s/

1 Answer 1

3

When you add parenthesis to a function, you call it. Not later, but right then and there, and you return what ever the function returns.

A function in javascript returns undefined by default, unless you explicitly return something else.

What you're really writing is

createButton("Submit", "content", "submitEnd", undefined);

The last undefined is because you called the function, it would be the same as

var result = test(); // undefined

createButton("Submit", "content", "submitEnd", result);

The way to solve it, is to reference the function, not call it

createButton("Submit", "content", "submitEnd", test);

See, no parenthesis.

FIDDLE

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

2 Comments

You should consider a career in education.
The best things in life are!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.