17

Why doesn't any javascript function written inside document.ready be directly called from an event in jsp?

Eg:

$(document).ready(function(){
     function abc()
     {
          //Some stuff here
     }
});

From something like:

<input id="a" type="button" onclick="abc();">
Pranav Kale
  • 629
  • 1
  • 5
  • 13
  • show your markup or make a fiddle – Tushar Gupta - curioustushar Aug 29 '13 at 07:03
  • 5
    Because it's out of scope. Attach the event _in JavaScript_. – elclanrs Aug 29 '13 at 07:03
  • Alternatively, move the function declaration outside of `document.ready`. There is no reason to put it there. – Felix Kling Aug 29 '13 at 07:24
  • @FelixKling you don't know that actually. Not with such a simplified code snippet. – Mchl Aug 29 '13 at 07:34
  • @Mchl: Fair enough, but I only see two reasons to keep a function declaration in there: If it is a closure and/or to keep the global scope clean. But aside from that, one does not have to wait to declare a function until the document is ready. I think there are many developers who put all their code inside the ready handler because they just don't know better. – Felix Kling Aug 29 '13 at 07:39
  • @FelixKling Agreed. I would usually assume such a function is a closure. – Mchl Aug 29 '13 at 07:42

1 Answers1

25

Because it's not available in the global scope. Any function defined within the anonymous function you pass as an argument to $.ready() is only available within that function.

To achieve what you want to do you need something like:

$(document).ready(function(){
     function abc() {}

     $('#a').on('click',abc);
});

For more information on function scope see this MDN article

Mchl
  • 61,444
  • 9
  • 118
  • 120