JavaScript JavaScript and the DOM Getting a Handle on the DOM A Simple Example

Vishesh Singh
Vishesh Singh
4,332 Points

Unexpected behavior of addEventListener() method.

I have tried to call a function in the addEventListener() method, as the second argument may be a javascript function ( I had checked details about the addEventListener() method on MDN ( , please check the detail about the parameter "listener")

My code is as below:

// selecting the myHeading element
 const myHeading = document.getElementById( "myHeading" );

// changing the color of the myHeading element
function eventClick( ) { = "red";

myHeading.addEventListener( "click", eventClick() ); 

Now, the problem is when I am previewing the HTML page, the red color is already applied to the heading element on the page load. Why such a strange behavior?

Above behavior is same if I convert the function declaration to a function expression and call it in the addEventListener() method.

2 Answers

Steven Parker
Steven Parker
171,047 Points

The code above calls the function (which makes the heading red) instead of passing it as a callback. To do the latter, omit the parentheses after the function name:

myHeading.addEventListener( "click", eventClick ); 

Hey Steven . I didn't got that. Can you please elaborate that.
I understood that if i used paranthesis , then heading will be red. But removing the parenthesis works. How?

Steven Parker
Steven Parker
171,047 Points

Without parentheses, the function is passed as a callback to the listener, and it will be called later by the listener when the event occurs.

Putting parentheses after the name calls the function immediately and passes whatever it returns as the callback parameter (which is not likely to be an appropriate parameter for the listener).

I am getting what you want to say . But I have a doubt as eventClick is a function not a variable. How is it will be called when the event occurs. Where does it mentioned in the code that eventClick will become eventClick() when the event happens?