9

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.

leigero
  • 3,233
  • 12
  • 42
  • 63
  • because you are calling it immediately `secondFunction()`, to pass a function you just use its name `secondFunction` – Patrick Evans Apr 08 '15 at 22:39
  • This is a function invocation vs function reference issue. More info: http://stackoverflow.com/questions/11757075/set-time-out-not-working-with-function/11757124#11757124 – Mitya Apr 08 '15 at 22:40
  • @PatrickEvans that's what I thought originally, but doing that doesn't run the function at all. – leigero Apr 08 '15 at 22:40
  • 1
    Then you need to look at your console for errors, for instance your jsfiddle is throwing an error because you have set it to have your code executed in the head and not using a dom ready event like onload – Patrick Evans Apr 08 '15 at 22:44

1 Answers1

14

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();
});
Mulan
  • 129,518
  • 31
  • 228
  • 259