JQuery explanation on document.ready - javascript

I have question will the click event or any other event run in document.ready() for the first time?
I mean will it reach after loading DOM elements to the comment without clicking first time? :)
$(document).ready(
$(#foo).click(
function()
{
// "It reached here after DOM is loaded!"
}
)
)

document.ready fires when the DOM is fully loaded, so you would be correct.
The 'click' event, however, will not fire unless the bound element is clicked or the click event is explicitly called using click() or Events/trigger:
$('#foo').click();
$('#foo').trigger("click");
Have you read the manual page for document.ready? See:
http://docs.jquery.com/Tutorials:Introducing_$(document).ready()

No, the function will not be executed.
There are a few errors:
$(document).ready() takes a function as an argument.
'#foo' should also be a string.
$(document).ready(function() {
$('#foo').click(
function()
{
// "It reached here after DOM is loaded!"
}
)
})
If you want the function to be evaluated at least once, after the dom loads. Then probably the easiest way is to name your function.
eg:
$(document).ready(function() {
$('#foo').click(
function myfunction()
{
// "It reached here after DOM is loaded!"
}
);
myfunction();
})
If you need the function to execute in the scope of $('#foo') you can do so with Function.call() method.
eg:
$(document).ready(function() {
$('#foo').click(
function myfunction()
{
// "It reached here after DOM is loaded!"
}
);
myfunction.call($('foo'));
})
That would make it behave more like as it were triggered by a DOM event. I'm sure JQuery has a specific method of triggering an event registered through it's DOM event functions. It would also be an option to use that as it would probably also emulate the Event Object passed to "myfunction".

To generalize the question, JavaScript events are handled by associating an event type (onclick, onkeyup, onfocuse, etc) with a function (or multiple functions). The function is, of course, parsed, but is not evaluated until the associated event occurs. Also, the "function," in this context, is often referred to as an event handler or event callback.

Related

Bind to ready event and another event with one anonymous function

Normally to bind multiple events to an element, one would use .on():
$("select#id").on("click change").function(){
// do actions
});
However, the use of ready with .on() is deprecated as of jQuery 1.8:
// Deprecated
$(document).on("ready", handler)
.on("ready") also behaves differently from .ready(). Specifically, handlers will not execute if .on("ready") is bound to elements after they are ready, whereas .ready() will execute even when called after the elements are ready.
You could accomplish it with a named function:
var myFunction = function(){
// do actions
};
$(document).ready(myFunction);
$("select#id").change(myFunction);
but that is less than ideal. Using a single anonymous function would be cleaner.
One method is:
$(document).ready(function(){
$("select#id").change(function(){
// do actions
}).change();
});
This will define the handler for the change event and then immediately call the change event. Because it's inside of the ready() handler, it will be executed for both ready and change events.
Sorry, you simply can't do it in more recent versions of jquery.
Your code as-is doesn't really make any sense, there's no reason to ever use anything other than document inside of $() when you're using .ready because .ready will simply ignore whatever is currently selected and perform it's action as if document were selected.
$(document).ready(function(){
$("#theid").change(changeHandler).change();
});
If the only goal is to only use 1 anonymous function, event delegation will do it, however it's probably overkill.
$(document).on('change','#theid',thehandler);
where thehandler is an anonymous function or a named function, you choose.

Basic jQuery understanding

What is the event
$(document).ready(function(){
$("a").click(function(event){
alert("Thanks for visiting!");
});
});
and also this one
$(document).ready(function(){
$("a").click(function(){
alert("Thanks for visiting!");
});
});
these two JS blocks are doing the same thing, but one with an event, if someone could explain what is function(event), also I saw something like function(e),function(g), what are those? Is there a tutorial I could learn?
The callback function that you're providing to $("a").click is a function that takes an argument. This argument is an event object containing details about the object. Your function declaration can take this argument with any name you like — event, e, g... and it can also simply leave it out since you're not using it inside of your function.
Consider that these two functions are essentially the same:
function foo(hi) {
alert(hi);
}
function foo(bye) {
alert(bye);
}
And that you may leave out the argument if it's not used:
function bar() {
alert("hello!");
}
bar(12345);
Event is an object that represents the... event that produced that function to be executed.
Here's more information about the topic:
http://api.jquery.com/category/events/event-object/
It is often used to prevent default behaviour of a certain event, or to stop the propagation of the event to parent objects:
function(e){
e.stopPropagation();
e.preventDefault();
}
The event in the first example is an unused argument.
jQuery passes various arguments into each event handler - you can find details of what these arguments are in the documentation (e.g. http://api.jquery.com/click/).
As you do not need to use the event object (or e, or g - you can give the parameter any name you want) then it doesn't matter whether or not you include it
However, if you needed to use the handler for some reason (e.g. to call event.preventDefault() to prevent the default click behaviour from happening) then you would need to include it.
jQuery passes eventObject to the handler/callback function which is not used in your example.
You could read more about the eventObject in JQuery.
Events : An event in JavaScript is something that happens with or on the webpage.
Example of events:
A mouse click
The webpage loading
Mousing over a hot spot on the webpage, also known as hovering
Selecting an input box in an HTML form
A keystroke etc...
Events in Jquery
Using e is just a short for event.You could use any variable say g instead of e
$('#xyz_id').click(function(g){
var clicked_target = g.target;
});
You could have a look at events in jquery further at
http://api.jquery.com/category/events/event-object/
event argument is a optional parameter and it can be any valid variable name. Based on your requirement you can pass or ignore it.
Visit http://api.jquery.com/click/ for more info.
.click( handler(eventObject) )
handler(eventObject)A function to execute each time the event is triggered.
version added: 1.4.3.click( [eventData], handler(eventObject) )
eventDataA map of data that will be passed to the event handler.
handler(eventObject)A function to execute each time the event is triggered.
version added: 1.0.click()

Can an event be be triggered if that event is attached to an element that doesn't exist

So, there are two important details to this question:
its inside the scope of document ready's callback function
the element that the event is attached to does not actually exist in the DOM
Here's a visual representation of the scenario
$(document).ready(function() {
$('#myNonExistentElement').on('click', function() {
//do something
});
});
Is it possible to programatically trigger that click event (via console or something else) under those circumstances?
I think the simple answer is no.
There are two cases which might, however, fit with your question:
1) If you just want to execute the event handler code, use a named function (instead of an anonymous function) and call it whenever you need to.
2) If you want to bind a click handler to an object that does not yet exist in the DOM but you know will in the future, you can use code like:
$(document).ready(function() {
$('body').on('click', '#myNonExistentElement', function() {
//do something
});
});
See the section about delegated events at http://api.jquery.com/on/
If you try to bind an event to an element that doesn't exist via jQuery (or at the very least, .on) no new event will be bound.
Sample case here.
*event code stolen from here because I'm lazy.

How do you change the event firing order of the same event?

Jquery bind is amazing, but I don't know in what order the binding happens. My current problem is thus:
$(document.body).delegate('form', methods.checkForm);
$('form').bind('submit', methods.submitFormIfCheckedFormIsTrue);
methods.checkForm = function (e) {
if (!$(this).isVerified()) {
return false;
}
return true;
};
methods.submitFormIfCheckedFormIsTrue = function (e) {
e.preventDefault();
$.ajax("/submitForm", {
data:$(this).serialize(),
type:"post"
});
};
This is obviously not the actual code that I'm using, but it's pretty close. What happens is, the submitFormIfCheckedFormIsTrue function fires before, or during, the checkForm function, so the checking is pretty useless. My hack for it was to add the class "checked" to the form and the check if the form has that class in the other function...but then you click submit, it checks, then you have to click it again to submit it if everything went right...which is retarded.
Another thing that's important regarding this problem is that I'm they're in completely different parts of my application, for reasons that can't change. Also, they're being loaded asynchronously.
The main thing I want to know then...is how to change the order, or set the priority of the events somehow...
If you are using 'delegate' the way you have it in your example, then the ajax submission is always going to run first, so the short answer to your question is "You Can't". Your delegate is attached to the 'body' element, so events attached to elements closer to the form in the DOM tree will fire first.
Events bubble from the form -> body, so there is no ordering when you are doing that.
One option would be to have your verification trigger a second event.
methods.checkForm = function (e) {
e.preventDefault()
if ($(this).isVerified()) {
$(this).trigger('form-verified');
}
};
Then instead of binding the other handler to 'submit', you would bind it to 'form-verified'.
$('form').bind('form-verified', methods.submitFormIfCheckedFormIsTrue);
This is also another way to accomplish ordering event if they are attached to the same element instead of using delegate.
Also, if you are using jQuery >= 1.7, then you should be using on instead of bind and delegate. http://api.jquery.com/on/
Update
If both are bound to the same element, then they will be triggered in the order that they were attached to the element. Assuming checkForm is bound before the other one, then the issue is that return false; does not stop other events from firing if they are attached to the same element. For that you also need e.stopImmediatePropagation().
methods.checkForm = function (e) {
e.preventDefault()
if (!$(this).isVerified()) {
e.stopImmediatePropagation();
}
};
There is also a useful answer over here if you ever have to tweak the ordering of events. jQuery event handlers always execute in order they were bound - any way around this?
In a general sense event handlers will be called in the order that they were bound, but only if they're bound at the same level. In your case you're binding one directly to the form while the other is a delegated handler bound at the document.body level. The directly bound one will happen first and then the event bubbles up to be handled by the other.
If you bind both handlers at the same level with .delegate() then they should be called in order:
$(document.body).delegate('form', 'submit', methods.checkForm);
$(document.body).delegate('form', 'submit',
methods.submitFormIfCheckedFormIsTrue);
Then in the first (generic) handler you should call the event.stopImmediatePropagation() method to prevent other handlers being called (noting that simply returning false prevents the default and stops the event bubbling up further, but it doesn't stop other handlers at that level from running):
methods.checkForm = function (e) {
if (!$(this).isVerified()) {
e.stopImmediatePropagation();
return false;
}
return true;
};
(By the way, the code shown in the question left out the event (second param) from the .delegate() call - I've put it in in my code.)
Or bind both handlers directly rather than using .delegate(). And speaking of using .delegate(), if you're using the latest version of jQuery you may like to switch over to using .on(), the new do-everything event binding method.
"What happens is, the submitFormIfCheckedFormIsTrue function fires before, or during, the checkForm function"
Definitely before, not during. (In pretty much all browsers) JavaScript runs on a single thread, so you will not ever have two functions running simultaneously.

Execute function on each item click, but also once on page load

I have a page with boxes and I want a function to run on each box click. Additionally, I want the function to run ONCE on page load.
(The idea is that the function "updates the state", and I want to update on each click, but also on page load - to initialize the state, so to speak.)
Normally, I do this like so:
$('.box').click(function() {
// do something
}).first().click();
So I attach the handler to each .box click event, and then I get the first .box element and trigger the click event on it.
This approach works, but it feels kind-of clumsy. How do you tackle this problem?
jQuery has triggerHandler()(docs), which offers a number of advantages that may be desired for your code.
$('.box').click(function() {
// do something
}).triggerHandler('click');
From the docs:
The .triggerHandler() method does not cause the default behavior of an event to occur (such as a form submission).
While .trigger() will operate on all elements matched by the jQuery object, .triggerHandler() only affects the first matched element.
Events created with .triggerHandler() do not bubble up the DOM hierarchy; if they are not handled by the target element directly, they do nothing.
Instead of returning the jQuery object (to allow chaining), .triggerHandler() returns whatever value was returned by the last handler it caused to be executed. If no handlers are triggered, it returns undefined
function hello() {
//Here goes your update function
alert('world');
}
$('.box').click(hello);
hello();
This is how I would probably do it.
(function(){
var foo = function(){
// stuff
}
$('.box').click(foo);
foo();
})();
Calls foo when it initializes and adds it to the click.
Something like this could also work :
$(document).ready(function($) {
$('.box').click(function() {
$(this).val("Value"); //Your function here
});
$('.box').each(function() {
$(this).val("Ready"); //Your function here
});
});
Demo

Categories

Resources