Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why in Javascript event handler functions with parentheses?

Javascript gurus, look at this code:

<button onclick="handler()">ClickMe</button>
        <script>
            function handler() {
            alert("clicked");
        }
     </script>

Why onclick event should be assigned to handler with () onclick="handler()"? In this case alert is called. But according to the logic described as answer to similar question https://stackoverflow.com/a/3247044/2543590 onclick assigned to result of function handler, not to function itself. I believe to assign onclick to function it should be like this

onclick="handler", 

but in this case alert is not called. Why?

like image 732
Vitaliy Markitanov Avatar asked Dec 10 '13 03:12

Vitaliy Markitanov


People also ask

What is the use of parentheses in JavaScript?

Description. The grouping operator consists of a pair of parentheses around an expression or sub-expression to override the normal operator precedence so that operators with lower precedence can be evaluated before an operator with higher precedence. As it sounds, it groups what's inside of the parentheses.

Why event handlers is needed in JS?

Event handlers can be used to handle and verify user input, user actions, and browser actions: Things that should be done every time a page loads. Things that should be done when the page is closed. Action that should be performed when a user clicks a button.

How do event handlers work in JavaScript?

Event handlers are the JavaScript code that invokes a specific piece of code when a particular action happens on an HTML element. The event handler can either invoke the direct JavaScript code or a function.

Which of the three JavaScript functions are event handlers?

Summary. There are three ways to assign an event handler: HTML event handler attribute, element's event handler property, and addEventListener() .


2 Answers

Anything you put inside onclick="" will be wrapped with an implicit function. That is the actual event handler that will be called on click, any function call inside it needs the parentheses.

like image 76
bfavaretto Avatar answered Oct 14 '22 11:10

bfavaretto


Because onclick="handler" isn't JavaScript. It's an attribute of your tag. Yes, if this were JavaScript, you'd be able to pass in the function itself, but it's not; you're assigning a statement to be executed on click.

The statement executed by onclick="handler" basically does this:

<script>
handler;
</script>

IE, nothing.

like image 30
meagar Avatar answered Oct 14 '22 10:10

meagar