Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write inline onclick function as es6 arrow function?

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?

like image 636
Cherry Blossom Avatar asked Dec 22 '22 16:12

Cherry Blossom


2 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.

like image 127
syedmh Avatar answered Dec 28 '22 23:12

syedmh


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

<button onclick="(()=>alert('hi'))();">Hi</button>
like image 34
cansu Avatar answered Dec 28 '22 22:12

cansu