Kiee
Kiee

Reputation: 10771

onclick firing on page load, need to call function with parameters

Sorry if this may be deemed a slight duplicate, however I couldn't find an answer that helped me understand why myFunc() is firing on page load and not when I click el1 or el2. How can I make the following code behave as expected?

function myFunc(param){
    //yadayada
}

el1.onclick = myFunc('string1');
el2.onclick = myFunc('string2');

Thanks.

Upvotes: 0

Views: 1562

Answers (1)

Josh Durham
Josh Durham

Reputation: 1662

document.getElementById('el1').onclick = function() { myFunc('string1'); };
document.getElementById('el2').onclick = function() { myFunc('string2'); };

You need to get the elements on the page first and then assign a function to them, otherwise the parser will execute them onload because it thinks that myFunc() is returning a value to be assigned to onclick as opposed to the actual function myFunc().

Upvotes: 2

Related Questions