How to write inline onclick function as es6 arrow function?

Viewed 3926

If this is duplicate let me know, but I see similar questions for react environment but not for pure html+js.

The question is, I write js function as html onclick property and it is working :

<button onclick="function myFunction(){ alert('hi')} myFunction();">Hi</button>

But I can't write arrow function as html onclick prop like that :

<button onclick="()=>alert('hi')">Hi</button>

It is possible or not?

3 Answers

You have to wrap it in parentheses and call it like an anonymous function in this way:

<button onclick="(() => alert ('hi'))()">Hi</button>

This is exactly how you would call an anonymous conventional function inline:

<button onclick="(function() { alert ('hi') })()">Hi</button>

The reason for this is, currently you've just declared a function, and every time you click, the function is declared but never called. With the adjustment in my answer, you define it and execute it each time a button is clicked.

Yes, it is possible. Just adjust parantheses, and you dont't need to define another function actually :

<button onclick="(()=>alert('hi'))();">Hi</button>

In the first example you assign a function to myFunction and then explicitly call myFunction.

In the second example you create a function, but you don't assign it anywhere, and you don't call it.

You could

onclick=" const myFunction = ()=>alert('hi'); myFunction() "

… but it is as completely pointless (and hard to read) as the first example.


There is no reason, in the scope of an onclick function or any other function to create a function and then call it once, immediately.


Just make the body of the onclick function do that directly:

onclick="alert('hi')"

Better yet, assign your event handlers using JavaScript:

document.querySelector("button")
    .addEventListener("click", () => alert("hi"));
Related