Javascript onclick function is called immediately (not when clicked)?

You want .onclick = secondFunction

NOT .onclick = secondFunction()


The latter calls (executes) secondFunction whereas the former passes a reference to the secondFunction to be called upon the onclick event


function start() {
  var a = document.createElement("a");
  a.setAttribute("href", "#");
  a.onclick = secondFunction;
  a.appendChild(document.createTextNode("click me"));
  document.body.appendChild(a);
}

function secondFunction() {
  window.alert("hello!");
}

start();

You could also use elem#addEventListener

a.addEventListener("click", secondFunction);

// OR

a.addEventListener("click", function(event) {
  secondFunction();
  event.preventDefault();
});

Leave a Comment