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.
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:
addEventListener
(such as IE8, which is sadly still a requirement for many), see this answer for a cross-browser event hooking function.data-*
attribute.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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With