Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

addEventListener calls the function without me even asking it to

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/

like image 333
LittleBobbyTables Avatar asked Apr 30 '13 23:04

LittleBobbyTables


People also ask

How do you call a function in addEventListener?

With the addEventListener() method you can specify the propagation type by using the "useCapture" parameter: addEventListener(event, function, useCapture); The default value is false, which will use the bubbling propagation, when the value is set to true, the event uses the capturing propagation.

How do you fix addEventListener is not a function?

To solve the "addEventListener is not a function" error, make sure to call the addEventListener() method on a valid DOM element, or the document or window objects, and place the JS script tag at the bottom of the body tag in your HTML.

Is it better to use onclick or addEventListener?

Both can be used to handle events. However, addEventListener should be the preferred choice since it can do everything onclick does and more. Don't use inline onclick as HTML attributes as this mixes up the javascript and the HTML which is a bad practice. It makes the code less maintainable.

How do I get rid of addEventListener?

Event listeners can also be removed by passing an AbortSignal to an addEventListener() and then later calling abort() on the controller owning the signal.


1 Answers

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.

like image 121
clav Avatar answered Oct 09 '22 04:10

clav