Zim
Zim

Reputation: 388

How to make nested functions public?

$(document).ready(function(){
    function example(){
        alert('Example');
    };
});
<a href='javascript:example();'/>

My problem is that the link won't call the function. I believe it's because example() is nested within another function. How do I fix this, without removing $(document).ready()?

Upvotes: 0

Views: 70

Answers (3)

Balachandran
Balachandran

Reputation: 9637

demo try in jquery

$(document).ready(function () {
   function example() {
       alert('Example');
   }

   $("a").on("click", example);

});

Upvotes: 1

Dan Sherwin
Dan Sherwin

Reputation: 723

$(document).ready(function(){
});
function example(){
   alert('Example');
};
<a href='javascript:example();'/>

Upvotes: 1

rvighne
rvighne

Reputation: 21897

Move the function declaration outside of the document.ready block.

Even if example() uses the DOM, the actual creation of the function doesn't need the DOM to be ready. And anyway, logically speaking, by the time the link is interactive, the function will have to have loaded.

Upvotes: 0

Related Questions