Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery function not defined - scope issue?

I have a likely simple problem that I need help with.

I have two js files that I have loaded on a page via tag in html. All the code in both these files is executed / loaded within $(document).ready();

On a certain event, function A defined in the first file tries to call function B defined in the other file. However, this fails, I get an error that function B is not defined.

I notice that if I take the definition of function B outside of $(document).ready(), that function A is able to call function B - it is in scope.

Why?

like image 804
gdbj Avatar asked Oct 09 '22 03:10

gdbj


1 Answers

It is a scope issue. Everything defined within a function is accessible only within that function unless made global in some other way. When you move the function outside of the ready function it becomes global making it accessible globally.

EDIT: When I say "made global in some other way", I mean something like this:

window.something = "something";

This will create a global variable something even if this line of code exists within your ready function.

like image 102
James Montagne Avatar answered Oct 13 '22 11:10

James Montagne