Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am trying to create a link, which looks and feels like an <a> tag item, but runs a function instead of using the href.

When I try to apply the onclick function to the link it immediately calls the function regardless of the fact that the link was never clicked. Any attempt to click the link thereafter fails.

What am I doing wrong?

HTML

<div id="parent">
    <a href="#" id="sendNode">Send</a>
</div>

Javascript

startFunction();

function secondFunction(){
    window.alert("Already called!?");
}

function startFunction() {
    var sentNode = document.createElement('a');
        sentNode.setAttribute('href', "#");
        sentNode.setAttribute('onclick', secondFunction());
      //sentNode.onclick = secondFunction();
        sentNode.innerHTML = "Sent Items";

    //Add new element to parent
    var parentNode = document.getElementById('parent');
    var childNode = document.getElementById('sendNode');
    parentNode.insertBefore(sentNode, childNode);
}

JsFiddle

As you can see I tried two different ways of adding this onclick function, both of which have the same effect.

like image 861
leigero Avatar asked Apr 08 '15 22:04

leigero


1 Answers

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();
});
like image 198
Mulan Avatar answered Oct 29 '22 23:10

Mulan