HTML and CSS Reference
In-Depth Information
Binding Events
One common use for callbacks is for binding event handlers. jQuery, as of version 1.7, provides a unified meth-
odology for attaching events in using $(selector).on . Because it does so much, $(selector).on has
a complicated definition with a number of optional arguments. The most common form is:
jQuery.on( events [, selector] [, data], handler )
Only two of the parameters are required: events and handler . The events parameter is a string of
comma-separated event names, but most commonly there will be only one name. Following is the simplest ex-
ample of calling $(selector).on for binding a click event to a link with an ID of start-button :
$("a#start-button").on("click",function(event) {
alert('Starting Game!');
});
Notice the standard selector $("a#start-button") followed by the event to be bound, "click" , and
then the callback.
The Special Case of Document Ready
Ensuring that your code runs at the proper time takes some care. If you try to run JavaScript that refers to DOM
elements that haven't been loaded yet, you'll be in trouble. Often you'll want to wait to run your JavaScript until
the whole page has loaded. This is before the window.onload event, which triggers after all assets and images
have loaded. You can use the standard event syntax to wait for this event:
$(document).on("ready",function() { ... }); but because it's so common, jQuery provides a
shortcut of just passing a function to the jQuery operator: $(function() { ... }) .
In some cases you need to prevent the event handler from taking the default action. In the preceding example,
you might not want the page to go to the href destination of the link you just clicked by default. In that case,
you need to tell the event that you don't want the default behavior to take place. You do this by calling pre-
ventDefault on the event object passed in as a parameter:
$("a#start-button").on("click",function(event) {
event.preventDefault();
alert('Starting Game!');
});
event.preventDefault is used most often for HTML elements with some default action, such as links,
inputs elements and forms, or with keyboard events where you don't want the page scrolling around.
If later you want to turn off any click events that you have bound to start-button , you can call
$(selector).off as shown here:
$("a#start-button").off("click");
This call turns off all click handlers on the button. If you want to turn off a specific handler, you need to pass
that handler as the second argument.
To follow up on the discussion of context in callbacks from the last section, jQuery intentionally changes the
this object in event callbacks to be the DOM element that triggered the event. This behavior is something you
must plan for if you need access to the context from outside of the callback.
If you want to hide the Start button after it is clicked, for example, you could write the following:
Search WWH ::




Custom Search