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() {
// ...
});
Related
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
I want to call jquery function in side of java script. My code is:
<script type="text/javascript">
function calljs(){
getUserMail(usermMail);
}
$(function() {
function getUserMail(usermMail) {
***some code*****
}
});
</script>
I got error from browser console:
ReferenceError: getUserMail is not defined.
How to solve this problem?
As far as i understand, the method is not defined when the method is being called. So define it before it is getting called
<script type="text/javascript">
function getUserMail(usermMail) {
***some code*****
}
function calljs(){
getUserMail(usermMail);
}
$(function() {
//
});
</script>
hope it helps
If it is really compulsory to put the function with in the jquery's ready callback (which I don't think is compulsory) use the following way
<script type="text/javascript">
var getUserMail = null;
function calljs(){
if ( null !== getUserMail ) {
getUserMail(usermMail);
}
}
$(function() {
getUserMail = function (usermMail) {
***some code*****
}
});
</script>
You can simply do ,
$(document).ready(function(event) {
getUserMail(usermMail);
});
and define it like ,
function getUserMail(usermMail){
. . .
}
or using jquery ,
$(document).on('click', ".selector", function);
trigger a function on an event
getUserMail is not defined in a scope that is accessible to calljs. This is why you get the ReferenceError; in the context in which you tried to invoke getUserMail there was no function with that name available.
// At this point nothing is defined
function calljs(){
getUserMail(usermMail);
}
// now calljs is defined as a global and can be invoked from anywhere
$(function() { // this line is calling a function named $ (an alias for jQuery)
// and passing it an anonymous function as a parameter.
function getUserMail(usermMail) { // This function is being defined inside
// the scope of the anonymous function,
// it can be used anywhere inside the
// anonymous function but not outside it.
// ***some code*****
}
});
// we are now outside the scope of the anonymous function,
// getUserMail is no longer in our scope and can't be called from here.
The easiest and likely best solution for most situations would be to make sure that any functions that call each other are in the same scope.
From what I can tell you don't really need calljs, you were just trying to use it to poke a hole into the scope of the anonymous function where getUserMail is defined.
Instead you should probably get rid of calljs and move any code that is calling getUserMail inside the ready callback. If getUserMail needs to wait for the ready callback to be fired before you call it, any code that invokes it also should be inside the ready callback too. (Things like event handlers that call it should already be inside the ready callback anyway.)
If there is a reason that you can't move it into the ready callback, such as something in another .js file needs to be able to call it etc, your application might be too complicated to be realistically maintained as jQuery soup. It might be worth the effort to port it to a framework such as Ember or Angular.
Also so you know, there is no need to use the type attribute on your script tags. JavaScript is the only language that has wide support in the browser and all browsers default to using JavaScript for script tags.
I am studying a JavaScript file and saw in it that some of the methods are wrapped inside a jQuery function. Can Anyone help me how to invoke the following method? And may I know what is the advantage or why the method is wrapped in a function? Below is my sample JavaScript code.
JQuery/JavaScript
$(document).ready(function () {
//How to invoke "testMethod" method?
$(function () {
function testMethod() {
alert("this is a test method");
}
});
});
As you've declared it, testMethod() is a local function and is only available inside the function scope in which it is declared. If you want it to be callable outside that scope, you will need to define it differently so that it is available at a broader scope.
One way of doing that is to make it a global function:
$(document).ready(function () {
//How to invoke "testMethod" method?
$(function () {
window.testMethod = function() {
alert("this is a test method");
}
});
});
testMethod(); // available globally now
It could also be attached to a global namespace or it could be defined at a higher scope where it would also solve your problem. Without specifics on your situation, we can't suggest which one would be best, but the main thing you need to do is to change how the function is declared so it is available in the scope in which you want to call it from.
P.S. Why do you have one document ready function nested inside another? That provides no extra functionality and adds unnecessary complexity. Also, there's really no reason to define testMethod() inside your document ready handlers if you want it available globally.
Before anything else:
$(document).ready(function(){...});
//is the same as
$(function(){...}}
As for your question, here's are potential ways to do it:
If that function is some utility function that everyone uses, then have it available to all in some namespace, like in this one called Utility:
//Utility module
(function(ns){
//declaring someFunction in the Utility namespace
//it's available outside the ready handler, but lives in a namespace
ns.someFunction = function(){...}
}(this.Utility = this.Utility || {}));
$(function(){
//here in the ready handler, we use it
Utility.someFunction();
});
If they all live in the ready handler, and want it to be used by all code in the handler, have it declared in the outermost in the handler so all nested scopes see it.
$(function(){
//declare it in the outermost in the ready handler
function someFunction(){...}
//so we can use it even in the deepest nesting
function nestedSomeFunction(){
someFunction();
}
someElement.on('click',function(){
$.get('example.com',function(){
someFunction();
});
});
nestedSomeFunction();
someFunction();
});
Your call needs to be within the $(function.
It's all about scope and you need to break the testMethod out of the $(function.
Can you perhaps further explain your requirement so that we can maybe help a little better?
Into ready event:
$(document).ready(function () {
//How to invoke "testMethod" method?
var testMethod = function () {
alert("this is a test method");
}
// V0.1
testMethod();
// V0.2
$('#some_id').click(testMethod);
});
In other part:
myObj = {testMethod: null};
$(document).ready(function () {
//How to invoke "testMethod" method?
myObj.testMethod = function () {
alert("this is a test method");
}
});
// Something else
if( myObj.testMethod ) myObj.testMethod();
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();
});
I have a block of code in $(function() { function parseData(){...} )};
I also have a function declared outside of the ready block. This is outside since I hook it up in codebehind ie ddlCategories.Attributes.Add("onchange", "getDataFields()");
From the getDataFields function, I need to call parseData but it does not seem to find it.
How do I access my parseData() which is in my ready block, from outside of the ready block?
(sorry if some of terminology is off - I am now to JS)
Any reason parseData() has to be in the ready block? Why not just make it a top level function:
<script type="text/javascript">
function parseData() { ... }
$(document).ready( function() {
ddl.Categories.....
}
<script>
Just define it outside your ready block. It's currently inaccessible due to the scope of the function.
Definitions can always safely go outside $(function() { ... }) blocks because nothing is executed.
$(function() { ... });
function parseData() { ... }
However, you seem to have a syntax error: )}; should be });.
Declare your parseData function outside of the self-executing $(function(){}); block.
var parseData = function () { ... };
$(function() { ... });
If there are things you need to reference inside the self-executing function, then declare the function globally but define it inside the self-executing function:
var parseData;
$(function() { parseData = function () { ... }; });
As an aside, declaring functions or variables globally is a bad idea.
You should declare the function outside the $(function() { ... }) callback.