Monday, June 3, 2024
30
rated 0 times [  34] [ 4]  / answers: 1 / hits: 57525  / 11 Years ago, tue, april 30, 2013, 12:00:00

So we have a page:



<span id='container'>
<a href='#' id='first'>First Link</a>
<a href='#' id='second'>Second Link</a>
</span>


And want to add some click events:



first.addEventListener('click', function(){alert('sup!');})


Works like a charm! However, when you make the second argument an external function:



function message_me(m_text){
alert(m_text)
}

second.addEventListener('click', message_me('shazam'))


It calls the function immediately. How can I stop this? So annoying!



Here's a live demo: http://jsfiddle.net/ey7pB/1/


More From » addeventlistener

 Answers
2

Quoting Ian's answer:




Since the second parameter expects a function reference, you need to provide one. With your problematic code, you're immediately calling the function and passing its result (which is undefined...because all the function does is alert and doesn't return anything). Either call the function in an anonymous function (like your first example) or alter the function to return a function.




function message_me(m_text){
alert(m_text)
}

second.addEventListener('click',
function() {
message_me('shazam');
}
);


Here's an updated fiddle.


[#78499] Monday, April 29, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
roberts

Total Points: 212
Total Questions: 101
Total Answers: 101

Location: Philippines
Member since Thu, Apr 14, 2022
2 Years ago
roberts questions
Sun, Feb 14, 21, 00:00, 3 Years ago
Tue, Dec 8, 20, 00:00, 4 Years ago
Wed, Jul 15, 20, 00:00, 4 Years ago
Wed, May 27, 20, 00:00, 4 Years ago
Mon, Apr 20, 20, 00:00, 4 Years ago
;