addEventListener calls the function without me even asking it to

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.

Leave a Comment