Vincent Dagpin
Vincent Dagpin

Reputation: 3611

Calling variable from other file in jquery

i have this index.html

    <script type="text/javascript" src="js/jquery-latest.js"></script>
    <script type="text/javascript" src="jqFunc.js"></script>
    <script type="text/javascript">

           var kamote = 6;

    </script>

and this jqFunc.js

$(function(){
   alert(kamote);
});

the problem is the value 6 wont appear.. what is way to call variables from other file like that?

Upvotes: 1

Views: 1604

Answers (3)

Pramendra Gupta
Pramendra Gupta

Reputation: 14873

I have tested , its working fine

<script type="text/javascript"  src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="jqFunc.js"></script>
<script type="text/javascript">
 var kamote = 6;
</script>

There might be a problem with

<script type="text/javascript" src="js/jquery-latest.js"></script>

ie js/jquery-latest.js file dont exits!

Upvotes: 3

Day
Day

Reputation: 9693

You have to put kamote in the global window object.

Try:

<script type="text/javascript" src="js/jquery-latest.js"></script>
<script type="text/javascript" src="jqFunc.js"></script>
<script type="text/javascript">
    window.kamote = 6;
</script>

and this jqFunc.js

$(function(){
    alert(window.kamote);
});

Upvotes: 0

Reigel Gallarde
Reigel Gallarde

Reputation: 65264

javascript is an interpreter. It will read your codes line by line and then execute it. You missed the logic there. You have assigned a value to a variable after alerting it. Which is not the thing you expected.

try this,

<script type="text/javascript">
   var kamote = 6;
</script>
<script type="text/javascript" src="jqFunc.js"></script>

and see what I mean. ;)

added notes:

but still you might get the desired output at some time. It is because you have wrapped your alert with the ready handler event. If your DOM takes long to be ready, alert will be 6. But if it's quick, you will not get 6.

Upvotes: 0

Related Questions