0

i have a index.php file

<!DOCTYPE HTML>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="test1.js"></script>
<script src="test2.js"></script>
</head>
<body>
</body>
</html>

test1. js is

$(document).ready(function(){

  alert('hello');
function check(){
    alert('hello i should also appear'); }
 });

And test2.js is

  $(document).ready(function(){

 check();
  });

hello is alerting , but hello i should also appear is not alerting , Can someone tell me what i am doing wrong here. thanks in advannce

2
  • Its in ready-scope. Put check outside ready. Commented Jan 4, 2017 at 14:05
  • In addition to the posted answers - note that this is nothing to do with multiple files - you could have all your code in one file and see the same issue. Commented Jan 4, 2017 at 14:07

5 Answers 5

3

Your function is defined inside of an anonymous function(){}, so it can be called just inside of its scope.

You should fix it and define the function outside of it:

// now it will be visible everywhere
var check;


$(document).ready(function(){

  alert('hello');
  check = function (param){
    alert('hello i should also appear. Param passed is ' + param); }
  });
});
Sign up to request clarification or add additional context in comments.

Comments

1

Under test1.js please write you function out of document.ready. functions which are written inside the document.ready cannot be accessed from out side. So you have to move it out from document.ready

function check(){
  alert('hello i should also appear'); 
}

Comments

0

You've defined "check" in a closure passed to the first call to document.ready(). The closure passed to the second call to document.ready() does not have access to the scope of the first closure, and in this particular case the function "check" only stays around for as long as the closure it is defined within.

You need to move your check function out of the closure and to a higher lexical scope where both closures can access it.

Comments

0

Change test1.js to

$(document).ready(function() {
    alert('hello');
});
function check() {
    alert('hello i should also appear');
}

and be sure to load test1.js before you load test2.js.

Comments

0

you should write function as global. If you write in document.ready() then that function scope limited so you cant access it from another javascript file

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.