Javascript event in a wrapper function for a html element

262 views Asked by At

I have the following issue: Let's say in my html page i have the following element:

<button onclick="myfunction(id)">Save</button>

and in my javascript file

(function(){

   function myfunction(id){
     // magic happends
   };

})();

In this case it's not going to work because the myfunction is wrapped in the iife function, so my question is: Is there a best practice in which you can keep your JavaScript logic inside a wrapper function and in the same time to be accessible to the HTML elments ?

1

There are 1 answers

1
Felix Kling On BEST ANSWER

Is there a best practice in which you can keep your JavaScript logic inside a wrapper function and in the same time to be accessible to the HTML elments ?

Depending on the structure of your app, the best way would be to not use inline event handlers but use the DOM API to bind the handler:

(function(){

   function myfunction(id){
     // magic happends
   };

   button.addEventListener('click', myfunction);
})();

More information about event handling.

If that's not possible and you really need to use inline event handlers, you can always make the function global:

(function(){

   window.myfunction = function myfunction(id){
     // magic happends
   };

})();