Having trouble with event listeners
Application Type

Hi there.

My first question is: when you assign an action as the handler for an element's event, should you include parenthesis or not?


element.onclick = $actions.OnElementClicked;

Is that alright? Supposing the action takes in some input parameters.

I ask this because I used parenthesis, and the action got executed when the element was never clicked. And then, when I ACTUALLY click on the element, nothing happens. So I thought maybe the parenthesis had something to do? Maybe if you include the parenthesis you are actually CALLING the function, and not assigning it as the event handler?

Any feedback would be appreciated.

Rank: #87

Hi there Yizuhi,

Hope you're doing well.

About your first question, the correct syntax is to include parenthesis. I always included them and never had problems :)

About your scenario, what is happening is since the second expression of the assign expects a function reference, you need to provide one. With your code, you are immediately calling the function and passing its result. That's why it triggers the function automatically and causes you problems afterwards. This should be the correct syntax:

object.onclick = function(){myScript};

So you should do something like this:

Element.onclick = function(){

I just did some tests and it is working like a charm :)

Hope that this helps you!

Kind regards,

Rui Barradas