The addEventListener function expects a function or an object implementing EventListener
as the second argument, not a function call.
When the ()
are added to a function name, it is a function invocation rather than the function itself.
Edit: As indicated in the other responses and in the comments, it is possible to return functions in Javascript.
So, for something interesting, we could try the following. From the original myAlert
, we can change it a little to return a different message, depending on the parameters:
function myAlert(msg)
{
return function()
{
alert("Message: " + msg);
}
}
Here, notice that the function actually returns a function. Therefore, in order to invoke that function, the extra ()
will be required.
I wrote a little HTML and Javascript to use the above function. (Please excuse my unclean HTML and Javascript, as it's 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 shown, and each will call the myAlert
function with a different parameter. Once the myAlert
function is called, it itself will return another function
so that must be invoked with an extra set of parenthesis.
End result is, clicking on Button1
will show a message box with the message Message: Clicked Button1
, while clicking on Button2
will show a message box saying Message: Clicked Button2
.