pokemon king
pokemon king

Reputation: 33

purpose of the "function()" for attaching a function to a eventlistener

Sorry if the question looks stupid, but I have been confused for long time.

I want to alert "viola" when the button is clicked. The second example below doesn't work as expected because I didn't include "function()"

Intuitively I think the second example should be working since I have attached a function(allert) to the element(button) and eventlistener(onclick).

Therefore I really wondered the purpose of including function(). Thanks.

Example 1

<html>
<button id="clickme">Hello,I'm a button,click me</button>


<script>
    var button=document.getElementById("clickme");

    clickme.onclick=function() {alert("viola");}


</script>
</html>

Example 2

<html>
<button id="clickme">Hello,I'm a button,click me</button>


<script>
    var button=document.getElementById("clickme");

    clickme.onclick=alert("viola");


</script>
</html>

Upvotes: 0

Views: 33

Answers (2)

Sebastian Simon
Sebastian Simon

Reputation: 19485

An event listener can only be a function.

alert("viola")

is not a function but actually undefined. That’s because

clickme.onclick=alert("viola");

means “assign the return value of alert(…) to clickme.onclick”. alert("viola") is being called immediately and the result of calling it is assigned.

The wrapper function(){…} actually assigns the function with the alert that is then called later.

Upvotes: 0

Kenney
Kenney

Reputation: 9093

clickme.onclick=alert("viola");

doesn't register the function alert(..), but the result of calling that function.

The onclick field expects a function, to be executed later, when the button is clicked. You don't want to execute that function when you're installing the handler. You could also write:

clickme.onclick=myfunction;

function myfunction() { alert("viola") }

Upvotes: 3

Related Questions