0

How can I call a function which is namespaced within a variable from html

<button onclick="hello()">Click me</button>

var app  = app || {};
(function($) {
    app.hello = function() {
         console.log("hello");   
    }
})(app, jQuery);

Fiddle - http://jsfiddle.net/5XMYD/5/

2 Answers 2

2

Like this:

<button onclick="app.hello()">Click me</button>

You need to select the no wrap in <head> or no wrap in <body> option in jsfiddle, or else your app variable will not have global scope and will not be accessible from your event handler:

http://jsfiddle.net/5XMYD/8/

With all that said, you should be using unobtrusive JavaScript, and not inline event handlers:

<button id="clickButton">Click me</button>

$(function() {
    $("#clickButton").click(app.hello);
});

http://jsfiddle.net/5XMYD/9/

Sign up to request clarification or add additional context in comments.

Comments

0

simply doing this should work

<button onclick="app.hello()">Click me</button>

Though for some reason it does not work in jsfiddle. Working fine in real environment.

1 Comment

It doesn't work in jsfiddle because the "onLoad" option is selected.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.