Reputation: 465
Can someone please explain the following syntax
$(function(){
$(".myPage").live("click", myHandler); // NOT THIS BIT!!
});
It looks globally defined, if that makes any difference?
Upvotes: 0
Views: 57
Reputation: 701
This function is attaching an event handler (myhandler) for all elements which match the current selector (.myPage), now and in the future. Read more about live on http://api.jquery.com/live/
Upvotes: 0
Reputation: 47099
$(function(){});
is a shorten for jQuery.fn.ready.
If you are working with multiply frameworks taht uses the $
it's so smart that it sends jQuery as the first arguments to to callback:
jQuery(function($) {
// $ is here 100% synonym for jQuery.
});
Inside the callback you bind an event to the selector .myPage
. But infact you are binding a selector to document and then checking to see if the event.target or event.target.parentN matches the selector:
Pseudo code:
$(document).on("click", function(event) {
if ( $(event.target).is(".myPage") || $(event.target).closest(".myPage") ) {
// call my original callback (myHandler)
}
});
Upvotes: 2
Reputation: 382102
$(somefunction)
asks jQuery to execute the somefunction
function once the DOM is ready.
From the documentation :
This function behaves just like $(document).ready(), in that it should be used to wrap other $() operations on your page that depend on the DOM being ready. While this function is, technically, chainable, there really isn't much use for chaining against it.
It ensures you don't try to access objects of the DOM before they're available. It's a good practice to embed your main code in such a callback, in a script element at the end of the body.
Note that you may have different scripts adding such blocks. All callbacks will be executed, in the order of insertion. This is especially important to know when you have a big applications with many scripts.
Upvotes: 1