Skip to content Skip to sidebar Skip to footer

Why Is A Function Declared In Document.ready() Not Defined When Called?

Here is my HTML/JavaScript:

Picture this:

<script>document.onload = function(){
    functionfoo(){
      alert('bar');
    }
  };
  foo();
</script>

That is the facsimile of what you're trying to accomplish. Just like variables defined within a function are off limits outside of it, function names take on the same characteristics.

Side-Note JavaScript doesn't require $ prefix on variable names (though is acceptable as far as names are concerned). I didn't know if you're coming from PHP and are just accustomed or were aware.

Thought I'd make my comment an answer.

Solution 2:

Try this:

$(function() {
    window.foo = function () {
        alert('bar');
    }
});

Basically, you need to expose the function to global scope.

Solution 3:

Variables and methods declared inside the $(function() function are only accessible within that. If you need to use those outside, you you make it in the global namespace like

window.functionName = functionName;

Solution 4:

You can not, it is private to that scope.

Solution 5:

What I ended up doing - what I should have done in the first place - is adding a click handler for the submit button:

$("input[name='submitButton']").click(function(){...});

Post a Comment for "Why Is A Function Declared In Document.ready() Not Defined When Called?"