Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call Javascript function from html file

I Have this JavaScript code:

var cr = {};
cr.plugins_ = {};
cr.runtime = null;

cr.plugins_.Vinoos_Markets = function(runtime) {
    this.runtime = runtime;
};
(function() {
	function initialize_events(result) {
		alert(result);
	}
})();
<button onclick="initialize_events('Test Result');">Send Result</button>

how to run 'initialize_events' function from html by clicking on button?

I don't have access to editing JavaScript file.

like image 552
Milad Mohammadi Avatar asked Dec 11 '22 10:12

Milad Mohammadi


1 Answers

i dont have access to editing js file.

Then you can't, full stop. It's entirely private to the anonymous IIFE* that encloses it. You'd have to expose it as a global in order to use it with an onxyz-attribute-style event handler (and that would require modifying the JavaScript code). It's one of the many reasons not to use them.

Since you can't do it without modifying the JavaScript, I'm going to assume you overcome that limitation and suggest what to do when/if you can modify the JavaScript:

Have that IIFE hook up the button, and use a data-* attribute if you need button-specific information to pass it:

var cr = {};
cr.plugins_ = {};
cr.runtime = null;

cr.plugins_.Vinoos_Markets = function(runtime) {
  this.runtime = runtime;
};
(function() {
  function initialize_events(result) {
    alert(result);
  }
  document.getElementById("send-result").addEventListener("click", function() {
    initialize_events(this.getAttribute("data-result"));
  }, false);
}());
<button id="send-result" data-result="Test Result">Send Result</button>

Notes:

  • If you need to support obsolete browsers without addEventListener (such as IE8, which is sadly still a requirement for many), see this answer for a cross-browser event hooking function.
  • If you have the data in the IIFE rather than the button, you can just use it directly rather than using a data-* attribute.
  • Giving the button an ID and using getElementById is just an example; in practice, anything that lets you identify the button is all you need. You can look up using a full CSS selector via document.querySelector.

* IIFE = immediately-invoked function expression, e.g., (function() { /*...*/})(); (Also sometimes called an "inline-invoked function expression." Also sometimes erroneously called a "self-invoking function," but it isn't; it's invoked by the code defining it, not by the function itself.)

like image 83
T.J. Crowder Avatar answered Dec 20 '22 20:12

T.J. Crowder