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
Related
Im trying to debug my web app that uses jQuery.
In firebug im calling functions inside the $(document).ready..
function val() { console.log('validated outside doc.ready'); }
$(document).ready(function()
{
console.log('document ready...');
function validate() { console.log('validated!'); }
}
In firebug console I type validate() and it says its not a function
If i type val() it works fine.
How do i call validate from the console ?
You are not calling a function like that, you just define the function.
The correct approach is to define the function outside document.ready and call it inside:
// We define the function
function validate(){
console.log('validated!');
}
$(document).ready(function(){
// we call the function
validate();
});
Another option is to self invoke the function like that:
$(document).ready(function(){
// we define and invoke a function
(function(){
console.log('validated!');
})();
});
Your validate function is local to the function you've passed to the jQuery ready handler.
if you do:
window.validate = function(){ /*....*/ };
you will be able to access from console. But it's not good practice to pollute the global scope unless it's just for debugging.
well, is there any reason you'd need that function inside document ready?
only inside those brackets (scope) the function will exist. just move it out, or all it only inside document.ready
You have 2 mistakes in your code.
Format to close bracket
You aren't calling the function. Calling the function is required to print it.
<script>
function val() { console.log('validated outside doc.ready'); }
$(document).ready(function() {
console.log('document ready...');
validate();
function validate() { val(); console.log('validated!'); }
});
</script>
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.
*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();
};
HTML
<button id='hello'>Click Me!</button>
JavaScript (wrong)
$('#hello').click(alert('Hello, World!'));
JavaScript (correct)
$('#hello').click(function() {
alert('Hello, World!');
}
I'm wondering why the first JS code triggers on the event load instead of click. Can anyone tell me why function() { [code] } is needed for the script to work properly?
In this example, I used jQuery events, but this is not specific to it, for example, I need to use it with setTimeout, too.
The click function expects another function as a parameter.
In the first case you would be passing the result of calling alert('hello world');, which is null.
The second is just a shorthand for:
$('#hello').click(callback);
function callback(){
alert('hello world');
}
Because .click() is a handler. The first argument is a function to assign. But if you actually pass the function with arguments then it will call the function (in this case alert) and then pass it's return value.
Writing $('#hello).click( function() { } )` is basically a short hand for writing:
var myfunction = function() {
// code
};
$('#hello').click( myfunction );
As you can see in the long hand way, it's passed as a reference to the function instead of the function's return value.
Your first example says "evaluate
alert('Hello, World!')
right now, and pass the result as an argument to click. "
The second says "Define a function which will do the alert when I call it, and pass that whole function as an argument to click.
The function() { ... } syntax is how you declare an anonymous function in Javascript. jQuery uses lots of these to specify that some action will be performed later, like when an event occurs. You can think of it as delaying the execution of your function until necessary. Without this syntax, whatever code you place there is evaluated immediately, which is not what you want for an event handler.
You might think, "why isn't JavaScript smart enough to know the difference?" Consider this:
function returnCallback(linkId, data) {
return function(e) {
alert('Clicked on ' + linkId + '. Here is some data: ' + data);
// Maybe do some stuff with e, the event parameter
}
}
$('#some-link').click(returnCallback('some-link', 'some-data'));
$('#other-link').click(returnCallback('other-link', 'different-data'));
This is a contrived example, but it illustrates the power of anonymous functions and closures. This works since returnCallback returns a function.
In the first instance, "JavaScript wrong", you're actually calling alert('Hello, World!') at the point that the script is loaded. Now, the reason you pass the .click function a function is because it can call it at any point. Essentially, you're packing code together to be run (or not run at all) at any point when you put it in a function.
$('#hello').click(alert('Hello, World!')); is attempting to run alert('...') and pass its return value to the .click() function which will not work as expected.
This is because JavaScript evaluates everything and during this process your alert is invoked. You can use anonymous function or you can also use your own custom function as implemented below:
<script language="javascript" type="text/javascript">
$("#mybutton").click(clickFired);
function clickFired() {
alert('click fired');
}
</script>
The parameter required for the .click() function is a Function. Therefore $("#hello").click(function { [code] }); is required. Because there's nothing to return by alert().
The click function here assigns a value to the event handler.
With the first ("wrong") code you're assigning a value of alert('Hello, World!') which is itself a function call, so it's going to be immediately evaluated and hence appear at load.
With the second ("correct") code you're now assigning a new anonymous function which is not executed itself, just instantiated at load. Hence this will work as expected later.
somefunction(alert('hello! world'));
this would mean you want to pass to somefunction the return value of alert("hello! world").
jquery click expects a callback that it should fire upon click on the element. so you put it in a function which does not execute unless someone (here jquery) calls it explicitly.
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.