Code-Lover
Code-Lover

Reputation: 309

Why is parentheses used for invoking function inside onClick tag of elements but not in onclick property of elements?

I have read in a book that we have not to use parentheses when assigning a function to onclick property of an element.

<input type="button" value="Click" onClick="sayHello();" id="button1">
var b1=document.getElementById("button1");
b1.onclick=sayHello;

Why do we use parentheses inside onClick attribute of above element?

Upvotes: 4

Views: 1048

Answers (2)

Mitya
Mitya

Reputation: 34556

Because of how inline events (i.e. specified as HTML attributes) work.

They're generally a bad idea for a multitude of reasons (see many related posts) but the answer to your question is this.

Events specified as HTML attributes are done so as strings. Essentially, when the element is clicked, the string specified as the attribute value is evaluated (this should give you a clue as to one of the reasons they're a bad idea). For this reason, you can think of the event causing the following JS to run:

sayHello(); //<-- invoke callback

If it caused instead the following to run, nothing would happen:

sayHello; //returns reference to callback, to nowhere

Upvotes: 4

Miles Grover
Miles Grover

Reputation: 609

If you wrote var b1.onclick=sayHello(); that would invoke the sayHello function immediately rather than waiting for the click event. You would want to use this technique if your sayHello function returns some value that you want to assign to the variable, though that would rarely be applicable when assigning the onclick property (it probably wouldn't make sense to be using the var keyword as you do in the example).

Technically, you could get the desired results from b1.onclick=sayHello(); if your code looked something like this:

<button id="b1">invoke sayHello</button>

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

    function sayHello() {
        return () => { console.log("hello"); };
    }

    b1.onclick=sayHello();
</script>

That would run the console.log whenever the b1 button is clicked.

In the case of HTML attributes, they are strings. You can think of assigning onClick in an HTML attribute as being roughly equivalent to this JavaScript:

b1.onclick = eval("sayHello()");

Upvotes: 1

Related Questions