Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
54
rated 0 times [  60] [ 6]  / answers: 1 / hits: 7464  / 4 Years ago, thu, november 12, 2020, 12:00:00

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?


More From » html

 Answers
7

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.


[#2313] Sunday, November 8, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kieraelsies

Total Points: 718
Total Questions: 103
Total Answers: 104

Location: England
Member since Sun, May 21, 2023
1 Year ago
kieraelsies questions
Tue, Aug 3, 21, 00:00, 3 Years ago
Tue, Feb 23, 21, 00:00, 3 Years ago
Wed, Sep 9, 20, 00:00, 4 Years ago
Mon, Sep 16, 19, 00:00, 5 Years ago
Fri, Sep 13, 19, 00:00, 5 Years ago
;