addEventListener calls the function without me even asking it to

addeventlistener call function with parameter
addeventlistener events
addeventlistener jquery
call function inside addeventlistener
addeventlistener mouseover
addeventlistener multiple events
removeeventlistener
addeventlistener is not a function javascript

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/

function message_me(m_text){
    alert(m_text)
} 

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

Here's an updated fiddle.

addEventListener calls the function without me even asking it to, function message_me(m_text){ alert(m_text) } second.addEventListener('click', function() { message_me('shazam'); } );. Here's an updated fiddle. If the call to the function is before to audioElement.addEventListener, it calls properly, but if the line ShowMedalMessage(1); is inside, it doesn't work : Thanks! javascript function audio addeventlistener

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.

You can do this:

function message_me(m_text){
    alert(m_text);
}

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

or this:

function message_me(m_text){
    return function () {
        alert(m_text);
    };
}

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

DEMO: http://jsfiddle.net/tcCvw/

Handling Events :: Eloquent JavaScript, Calling its addEventListener method registers the second argument to be called <button>Click me</button> <p>No handler here. For most types of events, the JavaScript event handlers are called before the default behavior takes place. To call a function with its parameters inside a function and just to invoke in that event you need to use the bind method like below: element.addEventListener("hover", logOnInput.bind(null, argument1, argument2, etc), false );

or you can use .bind

function message_me(m_text){
    alert(m_text);
}

second.addEventListener('click', message_me.bind(this, 'shazam'));

check MDN Documentation about 'closures'

addEventListener(), focus() getComputedStyle() matchMedia() moveBy() moveTo() open() print() prompt() addEventListener() method attaches an event handler to the document. Note: The addEventListener() method is not supported in Internet Explorer 8 and When passing parameter values, use an "anonymous function" that calls the  In a function invoked by addEventListener the value for this will automatically be set to the object the listener is attached to, productLineSelect in this case.. If that is what you want, you can just pass the function reference and this will in this example be select in invocations from addEventListener:

Modern ES6 solution using arrow functions

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

Bubbling and capturing, Why does the handler on <div> run if the actual click was on <em> ? The most deeply nested element that caused the event is called a target No matter where the click happened, it bubbles up to <form> and runs the handler. and some events even reach window , calling all handlers on the path. Note that there is no such thing as a "custom class method". object.method is still a normal function it will look like any other function to addEventListener.There is no implicit relationship between a function and the object to which it is assigned as property value.

What is `this` in event listeners? · Metafizzy blog, I was just asked: addEventListener( 'mousedown', function( event ) { // keep track of start to wrap up the draggable code into its own big function and call that for will reference the bound element as this , not the function or object. has served me well over the years, but I'm finding that I run into event  function: Required. Specifies the function to run when the event occurs. When the event occurs, an event object is passed to the function as the first parameter. The type of the event object depends on the specified event. For example, the "click" event belongs to the MouseEvent object. useCapture: Optional.

Adding an event listener | DOM events, Read and learn for free about the following scratchpad: Adding an event listener. </script> Not sure where I'm going wrong as I'm getting no errors but I'm not Can you use the "addEventListener" command to call a function with parameters​? On this page, when Pamela asked us to click the button, it didn't work for me. The EventTarget method addEventListener () sets up a function that will be called whenever the specified event is delivered to the target. Common targets are Element, Document, and Window, but the target may be any object that supports events (such as XMLHttpRequest ). addEventListener () works by adding a function or an object that implements

Solved: addEventListener function calling multiple times, Solved: I wrote a code to perform event handling using html id selector to The problem I'm facing is the function is getting called multiple times and thus the If not, give that a try - other scopes could easily result in that code firing By the way, can you tell me which is an efficient solution to this issue? The addEventListener () method attaches an event handler to an element without overwriting existing event handlers. You can add many event handlers to one element. You can add many event handlers of the same type to one element, i.e two "click" events. You can add event listeners to any DOM object not only HTML elements. i.e the window object.

Comments
  • 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). Either call the function in an anonymous function (like your first example) or alter the function to return a function (probably not ideal).
  • Why is this not ideal? It seems against D.R.Y. to copypasta my function in the 4 or so addEventListeners that im setting, no?
  • Another option is to store the required message as an attribute on the element, then bind the function as second.addEventListener('click', message_me) and have it retrieve the message from the attribute rather than from a parameter.
  • Possible duplicate of How to pass parameter to function using in addEventListener?
  • I think you should update your accepted answer because passing the function without calling it, and bind - is probably a better choice here.
  • Can you explain why you think bind is a better choice?
  • +1 binding should be the way to go — not sure if that was available 4 years ago, but is definitely the preferred way to today, as opposed to creating an anonymous function
  • Nice suggestion for the bind, definitely should be the accepted answer. Can OP change?