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.

4
  • because you are calling it immediately secondFunction(), to pass a function you just use its name secondFunction Commented Apr 8, 2015 at 22:39
  • This is a function invocation vs function reference issue. More info: stackoverflow.com/questions/11757075/… Commented Apr 8, 2015 at 22:40
  • @PatrickEvans that's what I thought originally, but doing that doesn't run the function at all. Commented Apr 8, 2015 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 Commented Apr 8, 2015 at 22:44

1 Answer 1

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();
});
Sign up to request clarification or add additional context in comments.

4 Comments

@leigero — the code in JS Fiddle doesn't match the code in this answer
@leigero: Of course your fiddle doesn't work. The answer however works.
@leigero yes it does work. See the appended snippet.
Thanks. Stupid mistake that was only made complicated by trying to trouble shoot it in JsFiddle.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.