Jquery function is not working due to $(document).ready

we have two js fie , test-1.js , test-2.js.

<script type="text/javascript" src="test-2.js"></script>
<script type="text/javascript" src="test-1.js"></script>

In test-1.js the code is

$(document).ready(function (){
     function test_alert(){  alert("hiii");  }
        });

In test-2.js

 $(document).ready(function (){
    function test_alert_2(){
          test_alert();
          alert("helloo");
        }

      });

but test_alert() not working in test-2.js . How to solve this ? Why this is not working ?

to solve this i rearranged

<script type="text/javascript" src="test-1.js"></script>
<script type="text/javascript" src="test-2.js"></script>

Now also , it is not working.I can not remove document.ready().

So i need a solution without removing document.ready()

Please help.

Answers:

Answer

call test-1.js before test-2.js .

Example

<script type="text/javascript" src="test-1.js"></script>
<script type="text/javascript" src="test-2.js"></script>
Answer

If you want to use code from test-1.js in test-2.js you have to load test-1.js first. JavaScript executes sequentially for synchronous code. So you can not access code from another scope (e.g. a file) if that code has not already been executed.

Answer

Adding this second answer because you changed the order to be correct, but then also changed the contents of the scripts. Since they both contain a $(document).ready(function() {...}); where you create the functions, this means the functions you create only exist in the scope of that function, e.g.

function foo() { 
  return 1;
}

$(document).ready(function() {
  // this is a new scope, functions created here will not be accessible outside of it.
  function bar() {
    return 2;
  }
});

foo(); // 1
bar(); // Error: undefined is not a function
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Answer

Here you have two JavaScript files and you are using a function in test-2.js file which is present in test-1.js file.Your test_alert function is not working because you called that functin before the js file completely loaded,Due to the file loading delay your test_alert() is not working.

Now ,you can use window.setTimeout() to solve this problem. Like:-

$(document).ready(function (){
    function test_alert_2(){
        window.setTimeout(function(){
            test_alert();
            alert("helloo");   
        },1000);

    }

});

Through this code the test_alert() will be called after one second of script load. I thing this Will Help You.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.