The second argument specifies a function to call when the event takes place. In this case, we use an anonymous function which tells console.log to print a notification that the event has taken place.
In Example 3, you can see that it appears that we have the syntax right. No errors appear when we run the code, but it still doesn’t work. It doesn’t work because the second argument must reference the listener that it intends to remove.
In Example 5, we use the removeEventListener method correctly. This time when a click event occurs, removeEventListener will remove the function bodyClickHandler which effectively eliminates the listener, and no clicks will generate a message.
These examples have demonstrated a simple piece of code that can do some powerful things. There are plenty of other events, besides clicking, that you can add listeners for, which can help make your application or website very dynamic. When using addEventListener to your code you can use an anonymous function to help make your code a little more precise and readable, but if you want to remove the listener after an event has occurred, you will need to use a named function for the second parameter.
If you have found these addEvenListener examples helpful, please share them on Facebook and Twitter.