Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling anonymous function in HTML

I have a question on pulling anonymous functions to an HTML. This is my HTML line of code:

onclick="functionToPull('map')"

functionToPull would be the name of the function if it was not anonymous. How do I pull an anonymous javascript function?

Example:

(function (){

})();
like image 380
sergey Avatar asked Mar 15 '17 00:03

sergey


1 Answers

Putting your event handler in the click event is considered a bad practice, except for frameworks like Angular. The recommended approach would be to create an event handler like so,

document.getElementById("myElement").addEventListener("click", function(){ alert("Hello World!"); });

But if you really want to do it that way, here's what you wanted:

<body>
    <button onclick='(function(){ console.log("Hello World"); })();'></button>
  </body>

You can see it in action in this plunker.anonymous function plunker

like image 169
Latin Warrior Avatar answered Sep 25 '22 15:09

Latin Warrior