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










0














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.










share|improve this question























  • because you are calling it immediately secondFunction(), to pass a function you just use its name secondFunction
    – Patrick Evans
    Apr 8 '15 at 22:39










  • This is a function invocation vs function reference issue. More info: stackoverflow.com/questions/11757075/…
    – Utkanos
    Apr 8 '15 at 22:40










  • @PatrickEvans that's what I thought originally, but doing that doesn't run the function at all.
    – leigero
    Apr 8 '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 8 '15 at 22:44
















0














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.










share|improve this question























  • because you are calling it immediately secondFunction(), to pass a function you just use its name secondFunction
    – Patrick Evans
    Apr 8 '15 at 22:39










  • This is a function invocation vs function reference issue. More info: stackoverflow.com/questions/11757075/…
    – Utkanos
    Apr 8 '15 at 22:40










  • @PatrickEvans that's what I thought originally, but doing that doesn't run the function at all.
    – leigero
    Apr 8 '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 8 '15 at 22:44














0












0








0







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.










share|improve this question















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.







javascript html onclick






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Apr 8 '15 at 22:39

























asked Apr 8 '15 at 22:38









leigero

2,46783355




2,46783355











  • because you are calling it immediately secondFunction(), to pass a function you just use its name secondFunction
    – Patrick Evans
    Apr 8 '15 at 22:39










  • This is a function invocation vs function reference issue. More info: stackoverflow.com/questions/11757075/…
    – Utkanos
    Apr 8 '15 at 22:40










  • @PatrickEvans that's what I thought originally, but doing that doesn't run the function at all.
    – leigero
    Apr 8 '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 8 '15 at 22:44

















  • because you are calling it immediately secondFunction(), to pass a function you just use its name secondFunction
    – Patrick Evans
    Apr 8 '15 at 22:39










  • This is a function invocation vs function reference issue. More info: stackoverflow.com/questions/11757075/…
    – Utkanos
    Apr 8 '15 at 22:40










  • @PatrickEvans that's what I thought originally, but doing that doesn't run the function at all.
    – leigero
    Apr 8 '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 8 '15 at 22:44
















because you are calling it immediately secondFunction(), to pass a function you just use its name secondFunction
– Patrick Evans
Apr 8 '15 at 22:39




because you are calling it immediately secondFunction(), to pass a function you just use its name secondFunction
– Patrick Evans
Apr 8 '15 at 22:39












This is a function invocation vs function reference issue. More info: stackoverflow.com/questions/11757075/…
– Utkanos
Apr 8 '15 at 22:40




This is a function invocation vs function reference issue. More info: stackoverflow.com/questions/11757075/…
– Utkanos
Apr 8 '15 at 22:40












@PatrickEvans that's what I thought originally, but doing that doesn't run the function at all.
– leigero
Apr 8 '15 at 22:40




@PatrickEvans that's what I thought originally, but doing that doesn't run the function at all.
– leigero
Apr 8 '15 at 22:40




1




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 8 '15 at 22:44





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 8 '15 at 22:44













1 Answer
1






active

oldest

votes


















3














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();
);





share|improve this answer






















  • @leigero — the code in JS Fiddle doesn't match the code in this answer
    – Quentin
    Apr 8 '15 at 22:46










  • @leigero: Of course your fiddle doesn't work. The answer however works.
    – slebetman
    Apr 8 '15 at 22:47










  • @leigero yes it does work. See the appended snippet.
    – user633183
    Apr 8 '15 at 22:47










  • Thanks. Stupid mistake that was only made complicated by trying to trouble shoot it in JsFiddle.
    – leigero
    Apr 8 '15 at 22:54










  • codepen.io/anon/pen/bNPGYv
    – Sai Phani
    Apr 8 '15 at 22:54










Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f29526556%2fjavascript-onclick-function-is-called-immediately-not-when-clicked%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









3














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();
);





share|improve this answer






















  • @leigero — the code in JS Fiddle doesn't match the code in this answer
    – Quentin
    Apr 8 '15 at 22:46










  • @leigero: Of course your fiddle doesn't work. The answer however works.
    – slebetman
    Apr 8 '15 at 22:47










  • @leigero yes it does work. See the appended snippet.
    – user633183
    Apr 8 '15 at 22:47










  • Thanks. Stupid mistake that was only made complicated by trying to trouble shoot it in JsFiddle.
    – leigero
    Apr 8 '15 at 22:54










  • codepen.io/anon/pen/bNPGYv
    – Sai Phani
    Apr 8 '15 at 22:54















3














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();
);





share|improve this answer






















  • @leigero — the code in JS Fiddle doesn't match the code in this answer
    – Quentin
    Apr 8 '15 at 22:46










  • @leigero: Of course your fiddle doesn't work. The answer however works.
    – slebetman
    Apr 8 '15 at 22:47










  • @leigero yes it does work. See the appended snippet.
    – user633183
    Apr 8 '15 at 22:47










  • Thanks. Stupid mistake that was only made complicated by trying to trouble shoot it in JsFiddle.
    – leigero
    Apr 8 '15 at 22:54










  • codepen.io/anon/pen/bNPGYv
    – Sai Phani
    Apr 8 '15 at 22:54













3












3








3






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();
);





share|improve this answer














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();
);





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();





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();






share|improve this answer














share|improve this answer



share|improve this answer








edited Apr 8 '15 at 22:47

























answered Apr 8 '15 at 22:42









user633183

67.9k21135175




67.9k21135175











  • @leigero — the code in JS Fiddle doesn't match the code in this answer
    – Quentin
    Apr 8 '15 at 22:46










  • @leigero: Of course your fiddle doesn't work. The answer however works.
    – slebetman
    Apr 8 '15 at 22:47










  • @leigero yes it does work. See the appended snippet.
    – user633183
    Apr 8 '15 at 22:47










  • Thanks. Stupid mistake that was only made complicated by trying to trouble shoot it in JsFiddle.
    – leigero
    Apr 8 '15 at 22:54










  • codepen.io/anon/pen/bNPGYv
    – Sai Phani
    Apr 8 '15 at 22:54
















  • @leigero — the code in JS Fiddle doesn't match the code in this answer
    – Quentin
    Apr 8 '15 at 22:46










  • @leigero: Of course your fiddle doesn't work. The answer however works.
    – slebetman
    Apr 8 '15 at 22:47










  • @leigero yes it does work. See the appended snippet.
    – user633183
    Apr 8 '15 at 22:47










  • Thanks. Stupid mistake that was only made complicated by trying to trouble shoot it in JsFiddle.
    – leigero
    Apr 8 '15 at 22:54










  • codepen.io/anon/pen/bNPGYv
    – Sai Phani
    Apr 8 '15 at 22:54















@leigero — the code in JS Fiddle doesn't match the code in this answer
– Quentin
Apr 8 '15 at 22:46




@leigero — the code in JS Fiddle doesn't match the code in this answer
– Quentin
Apr 8 '15 at 22:46












@leigero: Of course your fiddle doesn't work. The answer however works.
– slebetman
Apr 8 '15 at 22:47




@leigero: Of course your fiddle doesn't work. The answer however works.
– slebetman
Apr 8 '15 at 22:47












@leigero yes it does work. See the appended snippet.
– user633183
Apr 8 '15 at 22:47




@leigero yes it does work. See the appended snippet.
– user633183
Apr 8 '15 at 22:47












Thanks. Stupid mistake that was only made complicated by trying to trouble shoot it in JsFiddle.
– leigero
Apr 8 '15 at 22:54




Thanks. Stupid mistake that was only made complicated by trying to trouble shoot it in JsFiddle.
– leigero
Apr 8 '15 at 22:54












codepen.io/anon/pen/bNPGYv
– Sai Phani
Apr 8 '15 at 22:54




codepen.io/anon/pen/bNPGYv
– Sai Phani
Apr 8 '15 at 22:54

















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.





Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


Please pay close attention to the following guidance:


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f29526556%2fjavascript-onclick-function-is-called-immediately-not-when-clicked%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







這個網誌中的熱門文章

How to read a connectionString WITH PROVIDER in .NET Core?

In R, how to develop a multiplot heatmap.2 figure showing key labels successfully

Museum of Modern and Contemporary Art of Trento and Rovereto