call a javascript method in another .js file - javascript

what is the rule around calling functions from one js to another ? I thought that this worked but i am not running into issue (figured it out through firefox) that a function in another js file doesn't seem to be recognized in my first js file.
Is there some rule around ordering or some trick you have to do to get this to work?

It has to be accessible in the global scope somewhere. For example:
// file1.js
function hello() {
alert("Hello, world!");
}
// file2.js
$(function() {
hello();
});
Likely, you have something like this:
// file1.js
$(function() {
function hello() {
alert("Hello, world!");
}
// ...
});
// file2.js
$(function() {
hello();
});
hello is only in scope of the closure defined in file1.js. Therefore, to access it in file2.js, you'd have to export it to somewhere where file2.js can get at it:
// file1.js
$(function() {
function hello() {
alert("Hello, world!");
}
window.hello=hello;
});
// file2.js
$(function() {
hello();
});
Also, the script where the function is defined must be loaded, parsed, and executed before the function can be called from another script.

Are you calling the function in an event handler, or immediately when the javascript file is loaded? If it's not in an event handler, then load order is important. If you have circular dependencies, you may need to delay some of the initialization with a "DOM ready" or window.onLoad listener.

The browser parses the javascript files in the order they appear in the HTML. So if a function that is excecuted in the first file relies on a function that is in the second file it won't work. If you use $(function() {}); for example with jQuery this is instructing the javascript to wait until the onload event is fired from the window object. This ensures all the elements on the page have been loaded prior to execution.

Related

How to use jQuery to call a JavaScript function from another file

My question:
I have 2 files:
//Sub.js
function Second() {
//do something here
}
//Main.js
function One() {
//do something here
}
$(function() {
Second();
});
So basically, the function Second is too long; therefore, I want to move it to a Sub.js file and call it from the Main.js. The problem is this function ( function Second) has to be executed after function One because it gets some data from the function One output.
I don't know how to do this, please help.
If you specifically want to use jQuery,
$.getscript("Sub.js",function(){
Second();
});
<script src="/lib/Sub.js"></script>
<script src="/main.js"></script>
I think you should initialize firstly Sub.js before main.js in your head code.
Because whenever the page is first load js are intialize one by one.
You can include both the files in the page and on document ready call it sequentially:
$( document ).ready(function() {
var result = first();
second(result);
});
I was getting a similar problem. My solution was this. I was defining my function inside the .ready() callback. But The problem is that the functions is not accessible outside of its scope. To make this function available in the global scope (or through any object that is available in the global scope) is necessary declare outside the .ready() callback:
Wrong Way:
$(document).ready(function() {
function functionName () {
// ...
}
// ...
});
Right Way:
function functionName () {
// ...
}
$(document).ready(function() {
// ...
});

Javascript external function from html gives 'function not defined'

I'm trying to call a function within the html page from an external loaded index.js file, but I always get
Uncaught ReferenceError: displayy is not defined
Inside my html page:
<script type="text/javascript" src="index.js"></script>
<script>
$( document ).ready(function() {
displayy();
});
</script>
The index.js file:
$( document ).ready(function() {
alert('loaded');
function displayy() {
alert('executed');
}
});
I've also tried:
<script>
window.onload = function() {
displayy();
};
</script>
<script>
document.addEventListener("DOMContentLoaded", function(event) {
displayy();
});
</script>
You need not run displayy again from the script.
The following works:
$(document).ready(function() {
alert('loaded');
displayy();
function displayy() {
alert('executed');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Inside your index.js you can call your function using the window object.
window.displayy = function(){
return "hello!"
}
and then you call it
window.displayy(); or displayy();
A better solution is to declare your function in the higher scope like this:
var displayy;
$( document ).ready(function() {
alert('loaded');
displayy = function () {
alert('executed');
}
});
N.B: Using global variables are bad but it should solve your problem. Please take a look here: I've Heard Global Variables Are Bad, What Alternative Solution Should I Use?
Remove the document.ready wrapper in the .js file.
I ran into this problem, too. I had the call to the function in my main html file inside a document.ready and the external .js file was also wrapping the called function definition inside a document.ready function. Once I removed that wrapper in the .js file, it worked fine. This allowed the functions in the external .js file to become global in scope.
Attach your functions to the window object. Something like this:
// Set the container!
window.app = {};
// Define the function.
window.app.say_hello = function(name) {
alert(`Hello ${name}`);
};
// Call the function.
app.say_hello("Iran");
I tried everything. Only this solution worked. :)
You define the function on DOM ready, and this is useless and wrong.
Use the DOM ready event when you call your function, not when you define it:
Make sure they exist before the DOM is ready, then call them when DOM ready event is received.
So:
function definition -> at start (no need to wrap into event handler)
calling function -> at DOM ready
not the opposite

How to invoke a function in javascript which has been declared in a html file

I have a html file with function displayJsonWithAjax and function displayOtherJsonWithAjax declared in a script-tag.
In another script-tag, I invoke those functions with this code when a select box change:
<script>
import fetchJson from 'some.module'
function displayJsonWithAjax() {
...
}
function displayOtherJsonWithAjax() {
...
}
</script>
<script>
$(document).ready(function () {
$('#selectBox').change(function () {
displayJsonWithAjax();
displayOtherJsonWithAjax();
}).change();
});
</script>
When debugging with a browser, I get the following error:
ReferenceError: displayJsonWithAjax is not defined
If I try to put all the functions in the same script tag, no code is automatically executed when the browser load the page... How do I accomplish to call these two functions?
import fetchJson from 'some.module'
Does that really work? Check you console.
If a script line fails, everything after that line won't be executed, so the script functions won't be declared and won't be usable elsewhere (and that will explain why "If I try to put all the functions in the same script tag, no code is automatically executed when the browser load the page": the script fails at line 1, and nothing else is executed).
test();
<script>function test(){
alert('hello');
}</script>

Calling External function from within function - Javascript

I am using Phonegap and JQueryMobile to create a web application. I'm new to javascript and am having an issue.
My issue is with calling a function I have in a file named "testscript.js", the function is called testFunc. The testscript.js containts only this:
function testFunc() {
console.log("Yes I work");
}
Within my html page I have the following code:
<script>
$('#pageListener').live('pageinit', function(event)
{
testFunc();
});
</script>
The test function is found within my "testscript.js" which I am including with this line within the head tags:
<script src="testscript.js"></script>
The error I get is a "testFunc is not defined".
I am assuming its some type of scope issue as I'm able to call other jquery functions such as:
alert("I work");
and I am able to call my functions by sticking them within script tags in the html elsewhere.
I've tried all sorts of ways of calling my function with no success, any help is appreciated!
You must include the testscript.js before the other jquery code in your html. Like this:
<script src="testscript.js"></script>
<script>
$('#pageListener').live('pageinit', function(event)
{
testFunc();
});
</script>
As long as testscript.js has been loaded by the time PhoneGap fires the pageinit event, and provided the testFunc function is a global, there's no reason that shouldn't work.
You haven't shown us your testFunc, but my guess is that it's not a global, but rather you have it inside something like, for instance:
$('#pageListener').live('pageinit', function(event)
{
function testFunc()
{
// Do something here
}
});
or just a scoping function
(function()
{
function testFunc()
{
// Do something here
}
})();
Either way, since it's declared within another function, it's local to that function, not global. To call it from another script file, you'll need to be able to get at it from the global namespace (sadly). The best way to do that is not to make it a global, but to create just one global that you'll put all of your shared stuff on, like this:
(function()
{
if (!window.MyStuff)
{
window.MyStuff = {};
}
window.MyStuff.testFunc = testFunc;
function testFunc()
{
// Do something here
}
})();
...which you call like this:
$('#pageListener').live('pageinit', function(event)
{
MyStuff.testFunc(); // Or: window.MyStuff.testFunc();
});

Javascript / Jquery functions

Not sure if I am being totally wrong here but I want to do something like this:
Have an external js page (on an external server)
Include the page - OK that is easy etc...
Have a Jquery function on the external page - well actually many functions
Call those functions directly onto the page.
All a bit like this:
External js page:
$(document).ready(function() {
function testit() {
$('#test').load('page.php');
}
function testit_1() {
$('#test_1').load('page_1.php');
}
function testit_1() {
$('#test_2').load('page_2.php');
}
});
Then on the actual page just call:
<script type="script/javascript">
testit();
</script>
<div id="test"></div>
Am I wrong or should that not work?
You dont need to define the functions within the ready function, but you have to call it within the ready function.
$(document).ready(function() {
testit();
});
function testit() {
$('#test').load('page.php');
}
function testit_1() {
$('#test_1').load('page_1.php');
}
function testit_2() {
$('#test_2').load('page_2.php');
}
Otherwise testit() will be called before the document is loaded. And at that moment the function doesn't even exist yet in your example.
Your functions are local to the scope of the anonymous function passed as the argument to $(document).ready(). Here's a simple example showing the behaviour you're seeing:
(function() {
function foo() {
alert("It shouldn't alert this...");
}
})();
foo();
To fix it, simply move your function declarations outside of the ready function:
function testit() {
$('#test').load('page.php');
}
function testit_1() {
$('#test_1').load('page_1.php');
}
function testit_2() {
$('#test_2').load('page_2.php');
}
And use the ready function (shorthand $(function() { ... })) in your main js file:
$(function() {
testit_1();
});
I'm not sure if I'm understanding you wrongly, but will you load an external page of an external server? This is not possible on normal browser security settings. You cannot perform a succesful XMLHttpRequest for a document that resides on a different server. Nearly all browsers will block this and leave you with nothing. You would have to write a server-side proxy that fetches the document and serves it back to the client.
That should work fine. Just be sure to include the external JS file in your page and execute testit() inside another $.ready() call:
<script type="script/javascript" src="http://someurl.com/external.js"></script>
<script type="script/javascript">
$.ready( function() {
testit();
} );
</script>
<div id="test"></div>
The location of a JS file is irrelevant. Once it is loaded into your page, it is executed in the context of that page.

Categories