What is the difference between
$(function() {
// bind some event listeners
});
and
$(function() {
// bind some event listeners
}());
$(function() {
// bind some event listeners
});
In above case the function is passed to the jquery which will get executed once document is ready.
$(function() {
// bind some event listeners
}());
In above case the return of the function is passed to the jquery.
Since the function is se3lf executing itself, it will get executed immediately and whatever the function returns will get passed to the jquery, so this is not a good way because the objective is to execute the function once document gets ready which is not happening in this case
$(function(){...}); OR $(document).ready(function(){ ... });
This Function is called when the DOM is ready which means, you can start to query elements for instance. .ready() will use different ways on different browsers to make sure that the DOM really IS ready.
(function(){ ... })();
That is nothing else than a function that invokes itself as soon as possible when the browser is interpreting your JavaScript. Therefore, its very unlikely that you can successfully act on DOM elements here.
$(function() { ... });
is just jQuery short-hand for:
$(document).ready(function() { ... });
Immediately-invoked function expression (or IIFE), instead, are expression
"immediately executed", the convention is to enclose in parentheses, but every kind of expression is executed immediately, see following IIFE functions:
(function() {
console.log("IIFE 1");
}());
+function() {
console.log("IIFE 2");
}();
1-function() {
console.log("IIFE 3");
}();
var f = 50 * function() {
console.log("IIFE 4");
}();
I hope it was clear, bye.
$(function() {
// bind some event listeners
});
This one will be executed only when the DOM is fully loaded, it's the shortcut for :
$(document).ready(function(){
// Write code here
});
$(function() {
// bind some event listeners
}());
This one is the same but the function inside the $() is a self invoking function. Usually the goal is to prevent variable name conflicts, because it's creating a new scope.
Related
I started web development recently, and i can't seem to wrap my head around event handlers and callback functions. I understand that events handlers are a type of callback, and they respond to events unlike the more general definition of callbacks that get called by some other code when it finishes running. But, I'm looking for an explanation that 'sticks' with me.
Here's an example
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").hide("slow", function(){
alert("The paragraph is now hidden");
});
});
});
</script>
In this code example, i know that ready and click are both events so $("button").click(function(){ is an event handler for the ready event? and $("p").hide("slow", function(){ is an event handler for the click event? How about hide? is it also an event?
Yes, that's correct (took me a second to realize you were just showing the content of the handlers you were referring to). It's clearer if you don't define the handlers/callbacks inline, and you give them descriptive names:
function readyHandler() {
$("button").click(clickHandler);
}
function clickHandler() {
$("p").hide("slow", hideAnimationCompleteCallback);
}
function hideAnimationCompleteCallback() {
alert("The paragraph is now hidden");
}
$(document).ready(readyHandler);
Note that the code above is slightly different from your original, which looks more like this:
function readyHandler() {
function clickHandler() {
function hideAnimationCompleteCallback() {
alert("The paragraph is now hidden");
}
$("p").hide("slow", hideAnimationCompleteCallback);
}
$("button").click(clickHandler);
}
$(document).ready(readyHandler);
...but since none of the handlers/callbacks was relying on the fact it was created inside a handler/callback, it seemed clearer to show them completely independently. But it would matter if they were using something that's only in-scope within the handler they were created in.
Callback functions are what you described. Functions that are passed as parameters to another function and then later "called back".
Example:
file.read(fileName, function (err, data) {
// once file reading has finished, this function body is called,
// so this anonymous function is the callback
});
Event handlers are functions that gets triggered when a specific event occurs. It can be used for synthetic events, websocket events, and more. And its usual syntax is using callbacks.
Examples:
eventBus.on('new_message_arrived', function (err, data) {
// when 'new_message_arrived' event happens, this callback will be called
});
button.click((event) => {
// when button gets clicked, this callback (now used arrow function notaion)
// will be called with the details of the UI event
});
I playing around with a function that I want to bind to all the links. At the present the function fires when the page loads, instead of when I click on the link.
Here's my code. (I can post the function showDiv(), if you need to see it.) Can you tell if I'm doing something wrong or stupid here?
$(document).ready(function(){
$('a.test').bind("click", showDiv());
});
Thanks!
You want to pass a reference to a function as a callback, and not the result of function execution:
showDiv() returns some value; if no return statement was used, undefined is returned.
showDiv is a reference to the function that should be executed.
This should work:
$(document).ready(function() {
$('a.test').on("click", showDiv); // jQuery 1.7 and higher
$('a.test').bind("click", showDiv); // jQuery 1.6 and lower
});
Alternatively, you could use an anonymous function to perform a more advanced function:
// jQuery 1.7 and higher
el.on('click', function() {
foo.showDiv(a, b, c);
// more code...
});
// jQuery 1.6 and lower
el.bind('click', function() {
foo.showDiv(a, b, c);
// more code...
});
In some circumstances you may want to use the value returned by a function as a callback:
function function foo(which) {
function bar() {
console.log('so very true');
}
function baz() {
console.log('no way!');
}
return which ? bar : baz;
}
el.click(foo(fizz));
In this example, foo is evaluated using fizz and returns a function that will be assigned as the callback for the click event.
Looks like you're calling the function showDiv directly there (and binding the return result of showDiv() to the click handler instead of binding it directly.
You want something like
$(document).ready(function() { $('a.test').bind("click", showDiv); });
Use the below line. showDiv() will call the function rigth away when that line is executed.
$('a.test').bind("click", showDiv);
Change it to: $('a.test').bind("click", showDiv); (do not put parens around showDiv since you want to pass the function reference).
I playing around with a function that I want to bind to all the links. At the present the function fires when the page loads, instead of when I click on the link.
Here's my code. (I can post the function showDiv(), if you need to see it.) Can you tell if I'm doing something wrong or stupid here?
$(document).ready(function(){
$('a.test').bind("click", showDiv());
});
Thanks!
You want to pass a reference to a function as a callback, and not the result of function execution:
showDiv() returns some value; if no return statement was used, undefined is returned.
showDiv is a reference to the function that should be executed.
This should work:
$(document).ready(function() {
$('a.test').on("click", showDiv); // jQuery 1.7 and higher
$('a.test').bind("click", showDiv); // jQuery 1.6 and lower
});
Alternatively, you could use an anonymous function to perform a more advanced function:
// jQuery 1.7 and higher
el.on('click', function() {
foo.showDiv(a, b, c);
// more code...
});
// jQuery 1.6 and lower
el.bind('click', function() {
foo.showDiv(a, b, c);
// more code...
});
In some circumstances you may want to use the value returned by a function as a callback:
function function foo(which) {
function bar() {
console.log('so very true');
}
function baz() {
console.log('no way!');
}
return which ? bar : baz;
}
el.click(foo(fizz));
In this example, foo is evaluated using fizz and returns a function that will be assigned as the callback for the click event.
Looks like you're calling the function showDiv directly there (and binding the return result of showDiv() to the click handler instead of binding it directly.
You want something like
$(document).ready(function() { $('a.test').bind("click", showDiv); });
Use the below line. showDiv() will call the function rigth away when that line is executed.
$('a.test').bind("click", showDiv);
Change it to: $('a.test').bind("click", showDiv); (do not put parens around showDiv since you want to pass the function reference).
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();
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.