user962775
user962775

Reputation:

Calling nested JavaScript function through HTML (simple)

I know this is a duplicate topic, but this topic is different because i use very simple examples. I have a JavaScript function like this:

(function myfunction($){
    function a(){
        alert("A section"); 
    }
    function b(){
        alert("B section")
    }
})();

I want to create a HTML button which calls function A, and function B. How can i do that?

Upvotes: 0

Views: 98

Answers (4)

Xiaodan Mao
Xiaodan Mao

Reputation: 1706

You can create a variable first, and then expose it to global context:

(function myfunction($){
    var global = {
        a: function(){
            alert("A section");
        },
        b: function(){
            alert("B section")
        }
    };

    window.global = global;
})();
global.a();
global.b();

Upvotes: 0

Mehdi Karamosly
Mehdi Karamosly

Reputation: 5438

You can create an object that has these function and call your functions like below :

myFunctions = {

  a : function(){ alert("A section"); },
  b : function(){ alert("B section"); }

}

and then call them like below :

myFunctions.a();
myFunctions.b();

This is the jsfiddle to check it.

UPDATE:

As answer to your comment, this is an updated jsfiddle to show you how it works from HTML.

Upvotes: 1

smitrp
smitrp

Reputation: 1312

Assign function to global variables in closure is one way. Other way to do it is following.

(function myfunction($){
    $("#button1").click(function {
        alert("A section"); 
    });
    $("#button2").click(function {
        alert("B section"); 
    });
})(jQuery);

This doesn't spoil your global scope. And binds on click event for your buttons.

When not using jQuery

(function myfunction($){
    var button1 = getElementById("idOfButton1");
    button1.onclick = function {
        alert("A section"); 
    };
    var button2 = getElementById("idOfButton2");
    button1.onclick = function {
        alert("B section"); 
    };
})();

Upvotes: 0

Barmar
Barmar

Reputation: 781370

Make them global by declaring the names outside the closure, then assign them within the closure.

var a, b;
(function myfunction($){
    a = function() {
        alert("A section"); 
    }
    b = function() {
        alert("B section")
    }
})();

You can reduce the pollution of the global namespace by wrapping them in an object:

var myfuns = (function myfunction($) {
                 return { a: function() {alert("A section");},
                          b: function() {alert("B section");}
                        };
              })();

Then call myfuns.a and myfuns.b.

Upvotes: 2

Related Questions