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?
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With