Search code examples
javascripthtmlarrow-functions

Javascript define a function within event handler


How can I write a function within the onclick event of a button

What I want to do is something similar to this:

<button onclick="(function(){
     console.log('some code here')
 })">My button</button>


Solution

  • You'll need to invoke the function:

    <button onclick="(function(){
                         console.log('click')
                     })()">My button</button>