The addEventListener function expects a function or object that implements the EventListener as the second argument, not a function call.
When () added to a function name, it is a function call, not the function itself.
Edit: As pointed out in other answers and comments, functions can be returned in Javascript.
So, for something interesting, we could try the following. From the original myAlert we can change it a bit to return another message depending on the parameters:
function myAlert(msg) { return function() { alert("Message: " + msg); } }
Note here that a function actually returns a function. Therefore, to call this function, an additional () required.
I wrote some HTML and Javascript to use the above function. (Please excuse my unclean HTML and Javascript as this is not my domain):
<script type="text/javascript"> function myAlert(msg) { return function() { alert("Message: " + msg); } } </script> <html> <body> <form> <input type="button" value="Button1" onclick="myAlert('Clicked Button1')()"> <input type="button" value="Button2" onclick="myAlert('Clicked Button2')()"> </form> </body> </html>
Two buttons are displayed, each of which calls the myAlert function with a different parameter. As soon as the function myAlert is called, it will return another function , so it must be called with an additional set of brackets.
The end result: clicking on Button1 display a message box with the message Message: Clicked Button1 , and when you click on Button2 window will appear with the message Message: Clicked Button2 .
coobird
source share