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/
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.
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.
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.
Event listeners can also be removed by passing an AbortSignal to an addEventListener() and then later calling abort() on the controller owning the signal.
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 isalert
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With