Sorry for asking, but how do I access myFunction() from someFunction()?
<script>
$(document).ready(function() {
// Get messages
var myFunction = function() {
// doSth.
}
// Make the initial call on page load.
myFunction();
);
function someFunction() {
// Call the function a second time
myFunction(); // Call fails!
}
</script>
You are scoping it to the anonymous function you are passing to the ready method. Just move the definition outside that function.
Its more then a scope issue. Yes, you are scoping it to the anonymous function but even if you make it global by removing the var like this:
$(document).ready(function() {
// gets defined AFTER THE DOM IS READY
myFunction = function() {
// doSth.
}
}
// is called BEFORE THE DOM IS READY
myFunction();
It STILL won't work, because myFunction hasn't been defined by the time you call someFunction. someFunction is running immediately before the document is ready, which is BEFORE myFunction is defined.
Both functions need to be either in the document ready block, or outside it. If you need to manipulate DOM elements, I'd recommend inside.
If someFunction is called for a handler, you can remove the var declaration from myFunction and it will work as expected, because this will put myFunction in the global scope.
I don't think this will work because till the dom becomes ready and the document 'ready' event is fired the 'myFunction' function will not be created. The second call to 'myFunction' happens much before the 'myFunction' is created. This case will fail even if you create the function 'myFunction' in global namespace.
If you are not using any closure values inside your 'myFunction', you can move this function to global namespace. This will solve your ploblem.
Ex:
var myFunction = function(){
//Do somthing
}
$(document).ready(function(){
myFunction();
});
myFunction()
I think you wont be able to call myfunction() with your current code. You will have to get that function() { var myfunction = ... }; out of document.ready(). Seperate the method, then you can call myFunction.
Related
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 have this function in jQuery:
$(document).ready(function(){ function MyFunction() {alert('Hello!');} });
(For example only)
but, i'm want call this function with regular Javscript this way:
if(x == y){MyFunction();}
(For example only)
and i'ts not work.
However, When i try it:
function MyFunction(){alert('Hello!');} if(x == y){MyFunction();}
(Without jQuery function)
it's work.
Why?
if you put the function outside of the .ready() and call it in the ready function it will work, if you put it in the ready() and call it outside of ready it will give you an error you may have a function declared outside of ready state using jQuery code and call it inside.
function MyFunction(){
alert("hello!!");
}
//on ready
$(document).ready(function(){
if(x==y)
MyFunction();
});
I understand your issue like this {but not really clear what you are looking for imho}
Define function:
function MyFunction(){alert('Hello!');}
Call it on document ready:
$(MyFunction);
Now whenever you want, you could use:
if(x == y){MyFunction();}
this line:
if(x == y){MyFunction();}
should also be in the document.ready statement.
if you call it outside it will run before the function was actually defined and thus it will fail.
Lesonchi has it right. The issue is 'scope'.
The $(document).ready(...) call takes a function which is it's own scope (Javascript only has function scoping). So, anything defined inside the function you are passing to that call is ONLY available inside that function.
Based on your question, I assume you wanted to be able to call that MyFunction method elsewhere in the code and not just in the $(document).ready() - so, defining it outside the that call would give it 'global' scope, and hence could be used elsewhere in your code:
function MyFunction(){ /* do something */ }
$(document).ready(function(){
MyFunction(); // call it in this scope
});
// call it in 'global' scope
if (x == y) {
MyFunction();
}
See Also: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope
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();
*Is there a way to call a function defined inside another function in javaSCRIPT? For example:
window.onload() = function() {
function my_function(){
print("Blah");
};
};
function function_two(){
my_function();
};
Is there a way to do something like the above (calling my_function in function_two even though it's defined inside the window.onload() function)? In my actual code, which also uses the raphael.js library, I'm trying to write a button in HTML, which using the onClick function, calls a function(like function_two) that runs the function defined in window.onload() (like my_function). However the console says that the my_function is undefined.
The scope of the function is the core issue here, as Zeychin and Trevor have said. I thought I'd offer another way of handling it. Basically, you can set your function to a variable that's in a higher scope (that is, accessible to both the onload and function_two functions), while defining it inside the onload function as you originally have:
var myFunction; //This is the placeholder which sets the scope
window.onload() = function() {
myFunction = function() { //Assign the function to the myFunction variable
print('blah');
}
}
function function_two() {
myFunction();
}
This might be handy if you only know the information you need for myFunction once you're in the onload event.
You can not do what you are asking to do.
The function my_function()'s scope is only within the anonymous function, function(). It falls out of scope when the method is not executing, so this is not possible.
Trevor's answer is the way to do this.
window.onload = function() {
my_function()
};
function my_function(){
alert("Blah");
};
function function_two(){
my_function();
};
I have two external .js files. The first contains a function. The second calls the function.
file1.js
$(document).ready(function() {
function menuHoverStart(element, topshift, thumbchange) {
... function here ...
}
});
file2.js
$(document).ready(function() {
setTimeout(function() { menuHoverStart("#myDiv", "63px", "myIMG"); },2000);
});
The trouble is that this is not running the function. I need the two separate files because file2.js is inserted dynamically depending on certain conditions. This function works if I include the setTimeout... line at the end of file1.js
Any ideas?
The problem is, that menuHoverStart is not accessible outside of its scope (which is defined by the .ready() callback function in file #1). You need to make this function available in the global scope (or through any object that is available in the global scope):
function menuHoverStart(element, topshift, thumbchange) {
// ...
}
$(document).ready(function() {
// ...
});
If you want menuHoverStart to stay in the .ready() callback, you need to add the function to the global object manually (using a function expression):
$(document).ready(function() {
window.menuHoverStart = function (element, topshift, thumbchange) {
// ...
};
// ...
});
You have declared menuHoverStart inside a function (the anonymous one you pass to the ready ready). That limits its scope to that function and you cannot call it from outside that function.
It doesn't do anything there, so there is no need to hold off on defining it until the ready event fires, so you could just move it outside the anonymous function.
That said, globals are worth avoiding, so you might prefer to define a namespace (to reduce the risk of name collisions) and hang the function off that.
var MYNAMESPACE = {}; // In the global scope, not in a function
// The rest can go anywhere though
MYNAMESPACE.menuHoverStart = function (element, topshift, thumbchange) {