In this jsFiddle
am I trying to pass an argument to a function, but it doesn't receive the argument or it isn't executed.
Details
JQuery
$(document).ready(function() {
function addRemove(u) {
alert(u);
}
});
Any ideas what's wrong and how to fix it?
Your function only exists within the scope of the ready event handler, you need to move function addRemove outside of the ready function.
http://jsfiddle.net/EcCTx/2/
Your code was wrapped in an onload event by jsfiddle (drop-down menu on the left). So if you add a function it won't be global, but your onclick event calls a global function by the name addRemove.
You need to define your function outside of the $(document).ready().
I haven't tested it, but my guess is this: things inside of a function can't be accessed from outside of a function. For example,
$(document).ready(function() {
function addRemove(u) {
alert(u);
}
});
console.log(addRemove); // reference error or something similar
You should define addRemove function outside of $(document).ready.
the addRemove function must be outside of $(document).ready(function(){...});
In case Davin doesn't come back, here's the answer: jsFiddle defaults to wrapping your JS in the 'onLoad' method - and we can't allow that.
http://jsfiddle.net/nqbWe/
You had no defined function called addRemove in the Fiddle!
I've added this, and removed the inline javascript calls.
See this for better way of doing it:
http://jsfiddle.net/EcCTx/6/
There is nothing specifically calling that function. In the document ready part you have the function set up, but the anchor will not call that function by itself. In this instance it will only be called when someone clicks on that link.
You could give the link a class and data attribute and use those with jQuery to have something happen on page load.
Related
Sometimes I make a function and call the function later.
Example:
function example { alert('example'); }
example(); // <-- Then call it later
Somehow, some functions cannot be called. I have to call those functions inside:
$(function() { });
What do $(function() {}); and (function() { }); mean, and what's the difference/purpose of these?
$(function() { ... });
is just jQuery short-hand for
$(document).ready(function() { ... });
What it's designed to do (amongst other things) is ensure that your function is called once all the DOM elements of the page are ready to be used.
However, I don't think that's the problem you're having - can you clarify what you mean by 'Somehow, some functions are cannot be called and I have to call those function inside' ?
Maybe post some code to show what's not working as expected ?
Edit: Re-reading your question, it could be that your function is running before the page has finished loaded, and therefore won't execute properly; putting it in $(function) would indeed fix that!
The following is a jQuery function call:
$(...);
Which is the "jQuery function." $ is a function, and $(...) is you calling that function.
The first parameter you've supplied is the following:
function() {}
The parameter is a function that you specified, and the $ function will call the supplied method when the DOM finishes loading.
It's just shorthand for $(document).ready(), as in:
$(document).ready(function() {
YOUR_CODE_HERE
});
Sometimes you have to use it because your function is running before the DOM finishes loading.
Everything is explained here: http://docs.jquery.com/Tutorials:Introducing_$(document).ready()
Some Theory
$ is the name of a function like any other name you give to a function. Anyone can create a function in JavaScript and name it $ as shown below:
$ = function() {
alert('I am in the $ function');
}
JQuery is a very famous JavaScript library and they have decided to put their entire framework inside a function named jQuery. To make it easier for people to use the framework and reduce typing the whole word jQuery every single time they want to call the function, they have also created an alias for it. That alias is $. Therefore $ is the name of a function. Within the jQuery source code, you can see this yourself:
window.jQuery = window.$ = jQuery;
Answer To Your Question
So what is $(function() { });?
Now that you know that $ is the name of the function, if you are using the jQuery library, then you are calling the function named $ and passing the argument function() {} into it. The jQuery library will call the function at the appropriate time. When is the appropriate time? According to jQuery documentation, the appropriate time is once all the DOM elements of the page are ready to be used.
The other way to accomplish this is like this:
$(document).ready(function() { });
As you can see this is more verbose so people prefer $(function() { })
So the reason why some functions cannot be called, as you have noticed, is because those functions do not exist yet. In other words the DOM has not loaded yet. But if you put them inside the function you pass to $ as an argument, the DOM is loaded by then. And thus the function has been created and ready to be used.
Another way to interpret $(function() { }) is like this:
Hey $ or jQuery, can you please call this function I am passing as an argument once the DOM has loaded?
I think you may be confusing Javascript with jQuery methods. Vanilla or plain Javascript is something like:
function example() {
}
A function of that nature can be called at any time, anywhere.
jQuery (a library built on Javascript) has built in functions that generally required the DOM to be fully rendered before being called. The syntax for when this is completed is:
$(document).ready(function() {
});
So a jQuery function, which is prefixed with the $ or the word jQuery generally is called from within that method.
$(document).ready(function() {
// Assign all list items on the page to be the color red.
// This does not work until AFTER the entire DOM is "ready", hence the $(document).ready()
$('li').css('color', 'red');
});
The pseudo-code for that block is:
When the document object model $(document) is ready .ready(), call the following function function() { }. In that function, check for all <li>'s on the page $('li') and using the jQuery method .CSS() to set the CSS property "color" to the value "red" .css('color', 'red');
This is a shortcut for $(document).ready(), which is executed when the browser has finished loading the page (meaning here, "when the DOM is available"). See http://www.learningjquery.com/2006/09/introducing-document-ready. If you are trying to call example() before the browser has finished loading the page, it may not work.
I have a button on which I want to attach an event listener. I also need to pass a extra parameter url to this function. I read about apply and I'm doing the following:
$('#list-button').on('click',postListing.apply([url]));
My problem is that as soon as this script is loaded postListing is called. I am not calling the function anywhere else. I need it to be called only on click.
The difference between bind and call/apply is that bind doesn't call the function immediately much like it loads the data with the variable when needed
You can reformat your code so it looks like this
$('#list-button').on('click', postListing.bind(this, url));
Found a way. It can be done using a closure:
var postListing = function(event, url){
return function(){
//Main functionality wrapped here
};
};
And the event listener setting remains the same:
$('#list-button').on('click',postListing.apply([url]));
I'm still confused sometimes by the way events are handled. I just wondered how to pass the event to it's handler.
The following example just works fine:
$(document).on('click', "div#foo", function(event) {
event.preventDefault();
});
But how to pass the event to an handler specified by name, like:
// this obviously wont work
$('div#foo').on('click', fooClick);
function fooClick(event){
event.preventDefault();
}
Thanks for your insights!
Your second example is exactly how to do it and that will work just fine.
It is the responsibility of .on() to set up the arguments to the callback it calls and what is passes has absolutely nothing to do with how you declare your callback. The first argument to the callback function will be the event object no matter how the callback is declared.
So, this will work just fine:
function fooClick(event){
event.preventDefault();
}
// this works just fine
$('div#foo').on('click', fooClick);
Working demo: http://jsfiddle.net/jfriend00/BWKde/
What's important to understand is that when you pass fooClick as the second argument to .on(), you are just passing a function reference. It is .on() who decides how to call that function reference and what to pass it.
FYI, your selectors will generally perform better if you pass just #foo, not div#foo unless you specifically want to only match #foo if it's in a div tag. Since id values can only be used once in a given page, you usually don't need to qualify them further and doing so just makes more (unnecessary) work for the selector engine.
your code is ok,
check at http://jsfiddle.net/9266U/ and read more at https://api.jquery.com/on/
$('div#foo').on('click', fooClick);
function fooClick(e){
alert("it work, nevrx");
e.preventDefault();
}
Javascript is synchronous, try to put it like this:
function fooClick(event){
event.preventDefault();
}
$('div#foo').on('click', fooClick);
I am currently making use of Simon Willson's addLoadEvent function to add functions that I want to run after the load event. I ran into a problem wherein the the function I passed to the addLoadEvent function referenced a div that had not yet been loaded by the DOM and so my action (showing the div) did not do anything. When I changed to using the jQuery $(document).ready function, the div has been loaded by the DOM and I can execute actions with it (make it show up).
So, a couple questions. Why is my function being executed before the DOM has completed loaded using the above function? Is there a way to delay it? The other alternative that I can think of is passing in a function to a jquery equivalent:
function jqueryAddReadyEvent(myFunc)
{
$(document).ready(function()
{
//execute already existing functions
//add a new function to the ready event
myFunc();
}
}
When I try the above code, I get a javascript error "myFunc is not a function". Is there a way to generically pass in a function to the jquery ready function and have it execute? Equivalent to the following:
$(document).ready(function()
{
funcA();
}
$(document).ready(function()
{
funcB();
}
...//more of the same
Replaced with the following:
jQueryAddReadyEvent(funcA);
jQueryAddReadyEvent(funcB);
You can just do:
$(document).ready(myFunc);
to attach functions to the DOM ready event. Here's the fiddle: http://jsfiddle.net/padtE/
If you will require many functions to be added then I suggest you do the following:
Create an array that will old all the functions you want to call.
Add functions to that array as you please.
In the .ready(function() { ... }) call every function in that array.
You're set.
It looks correct to me. Most likely you are calling it with something not a function.
Btw you can shorten this to:
var jqueryAddReadyEvent = $(document).ready
or just use $(document).ready() directly for the same effect, as it specifically does what you want to do, run functions after the load, and is actually shorter.
$(document).ready(funcA);
$(document).ready(funcB);
function jqueryAddReadyEvent(myFunc) {
$(myFunc);
}
jqueryAddReadyEvent(function() {
alert('hello world');
});
Demo: http://jsfiddle.net/AlienWebguy/UzMLE/
I have the following in a javascript file (using jQuery as well):
$(function(){
$('#mybutton').live('click',myObject.someMethod);
});
var myObject = {
someMethod: function() { //do stuff }
};
I get a js error on pageload that says "myObject isn't defined". However, when I change the event handler in the doc.ready function to:
$('#mybutton').live('click', function(){ myObject.someMethod(); });
it works! I have code structured like the first example all over my codebase that works. W T F??
In the first code block, you're trying to assign the value of myObject.someMethod (which is declared after this code block) to the second parameter for live().
When you wrap it in an anonymous function, as in the second block, the anonymous function doesn't get executed until the live event gets triggered. myObject.someMethod has been created by this point, so the code works as expected.
In the second case the lookup on myObject is deferred until the point at which the click handler is executed. In the first case, (in some cases, see below) the lookup must be immediate... as myObject is not yet defined, you get an error. Is there any reason not to add the event handler after myObject has been declared and assigned?
EDIT
As commented above, is it possible that this code is running after the .ready() event has fired.
jQuery docs say this about the .ready() method:
If .ready() is called after the DOM has been initialized, the new handler passed in will be executed immediately.
In this case, your ready handler will fire synchronously, thus requiring myObject to be defined.
Maybe the document.ready scope has another variable named myObject which hides the original one?