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.