Reputation: 11
I have this codes
//first.js
var site = {};
//and functions are declared like that
site.functionNames = function(){
//some codes
};
//second.js
$("#element").click(function(){
//more codes
site.function;
site.function();
console.log(site);
});
How can I access/call first.js functions from the second.js click event? Tryed the ones above but all say site is undefined. Dont know if is the right way.
:Edit:
Files are already declared in order, second.js comes after some others.
<script src="first.js" type="text/javascript"></script>
<script src="second.js" type="text/javascript"></script>
Upvotes: 0
Views: 1801
Reputation: 48207
this is a working example
Test.html
<!DOCTYPE html>
<html class="html" lang="es-ES">
<head>
<script src="scripts/jquery-1.8.3.min.js" type="text/javascript"></script>
<script src="tfirst.js" type="text/javascript"></script>
<script src="tsecond.js" type="text/javascript"></script>
</head>
<body>
<div class="fieldwrapper" name="field1" id="field1" />
First name: <input type="button" name="first" onclick="site.functionNames('html')"><br>
Last name: <input type="button" name="second" id="other"><br>
</div>
<body>
</html>
tfirst.js
var site = {};
//and functions are declared like that
site.functionNames = function(v){
alert("hello " + v);
};
tsecond.js
$(document).ready(function(){
$("#field1").on('click', '#other', function () {
site.functionNames('second.js');
console.log(site);
});
});
Upvotes: 0
Reputation: 25
The browser is reading script
tags in the order they are written, unless async
is true
. so just place your script tags the way you want and the browser will execute the second one after the first one.
Edit:
Maybe there's an error loading the js file. Check in the browser dev tools.
Upvotes: 0
Reputation: 1639
A function cannot be called unless it was defined in the same file or one loaded before the attempt to call it.
A function cannot be called unless it is in the same or greater scope then the one trying to call it.
You declare function fn1 in first.js, and then in second you can just have fn1();
1.js :
function fn1 (){
alert();
}
2.js :
fn1();
index.html :
<script type="text/javascript" src="1.js"></script>
<script type="text/javascript" src="2.js"></script>
Source: Calling a javascript function in another js file
Upvotes: 0
Reputation: 48207
As long you declare the javascript file in order you should be able to use it.
<head>
....
<script src="first.js" type="text/javascript"></script>
<script src="second.js" type="text/javascript"></script>
....
<head>
If you invert the order, wont work
<script src="second.js" type="text/javascript"></script>
<script src="first.js" type="text/javascript"></script>
Upvotes: 3