Commonly used event handlers
Event handlers
Web pages are typically built using an event based architecture. An event is something that occurs where we, as the developer, don't have direct control over its timing. Unlike a classic console application, where you provide a list of options to the user, in a time and order that you choose, a web page presents the user with a set of controls, such as buttons and textboxes, that the user can typically click around on whenever they see fit. As a result, being able to manage what happens when an event occurs is critical.
Fortunately, in case you hadn't already guessed, jQuery provides a robust API for registering and managing event handlers, which is the code that will be executed when an event is raised. Event handlers are, at the end of the day, simply JavaScript functions.
Registering event handlers
jQuery provides several ways to register an event handler. As we saw in Module 1, the most common way of registering an event handler is to call the function on the jQuery object that corresponds to the event you wish to capture, such as
click
. You will notice that the jQuery APIprovides functions for almost any JavaScript or DOM event.
We will discuss many of these event handlers as we continue on with the course, but we won't cover every function available - that would take quite a while, and probably bore almost everyone. But we will cover the ones you'll use most frequently. In addition, we'll also cover the various ways you can register an event handler, which will have an impact on the way that you write your code in many scenarios.
Event objects
Discovering more about the event
When you register an event handler from a location other than the object that will be raising the event, there's a disconnect between those two objects. If you're maintaining a 1:1 ratio between event handlers and events, meaning that each event that you're interested in has its own function, then generally there isn't an issue in assuming you know exactly what happened, and on what object it happened to.
However, even if you are maintaining that 1:1 ratio, that can be a brittle relationship. If something changes on the object, your code might not work with the updates that have been made.
In addition, you will often reuse a single event handler for multiple events. The power of the selector syntax supported in jQuery allows you to wire up event handlers for events raised by numerous controls in one line of code. The code below would register the anonymous function with every element decorated with the sample
class. The number of elements with that class could change over the course of the page's development, or even the execution of other scripts.
$('.sample').click(function() { alert('Hello!'); });
When creating event handlers, it's often best to not make any assumptions about the object that raised the event, even its ID. Not only can things change that might break your code, if you avoid this link between the event handler and the object your code can become both more reusable and flexible.
sample
class. The number of elements with that class could change over the course of the page's development, or even the execution of other scripts.
$('.sample').click(function() { alert('Hello!'); });
this
As we've already discussed, when you're inside of an event handler, this
is automatically assigned to the object that raised the event.
The most important thing to remember about this
is it will be a DOM object, not a jQuery object. This means all of the power jQuery provides won't be available direclty off this
. In order to use jQuery with the object, it needs to be converted to a jQuery object. This is accomplished by simply calling $(this)
.
The sample below would update the text of the button that was clicked to Clicked!!.
<button type="button">Click!</button>
$('button').click(function() {
// this is linked to button that was clicked, but is a DOM object
// convert it to a jQuery object by using the jQuery factory
$(this).text('Clicked!!');
});
this
is automatically assigned to the object that raised the event.this
is it will be a DOM object, not a jQuery object. This means all of the power jQuery provides won't be available direclty off this
. In order to use jQuery with the object, it needs to be converted to a jQuery object. This is accomplished by simply calling $(this)
.<button type="button">Click!</button>
$('button').click(function() {
// this is linked to button that was clicked, but is a DOM object
// convert it to a jQuery object by using the jQuery factory
$(this).text('Clicked!!');
});
event object
Beyond just the object that raised the event, jQuery (and JavaScript) also pass an event
object to the event handler. This object can be used to determine additional information, such as where the mouse was when the user performed the operation. You might use that information to create hotspots on an element. The event object offers many properties you can query.
// Write out the x/y coordinates of the mouse on click
$('button').click(function(e) {
$('#output').text(e.pageX + 'x' + e.pageY);
});
Click
event
object to the event handler. This object can be used to determine additional information, such as where the mouse was when the user performed the operation. You might use that information to create hotspots on an element. The event object offers many properties you can query.// Write out the x/y coordinates of the mouse on click
$('button').click(function(e) {
$('#output').text(e.pageX + 'x' + e.pageY);
});
Common event handlers
jQuery allows you to use functions to "wire up" event handlers to most every JavaScript or DOM event. Here are some of the most common ones you'll use when creating code using jQuery
click
By far, the most common event handler is click
. click
, of course, is raised whenever the user clicks on an item, either by using their mouse or tapping on it with their finger. You can register click
for nearly any HTML control, not just buttons. This allows you to "convert" other objects, such as div
elements, into buttons. You can use this to provide the rich UI you want without being locked into using specific HTML controls, or essentially create your own controls.
To register the click
event, simply use the click
function.
$('#target').click(function() { alert('hello, world!'); });
click
. click
, of course, is raised whenever the user clicks on an item, either by using their mouse or tapping on it with their finger. You can register click
for nearly any HTML control, not just buttons. This allows you to "convert" other objects, such as div
elements, into buttons. You can use this to provide the rich UI you want without being locked into using specific HTML controls, or essentially create your own controls.click
event, simply use the click
function. $('#target').click(function() { alert('hello, world!'); });
dblclick
As the name implies, dblclick
is raised when the user double clicks on an element. The dblclick
event can be helpful when creating an application that is designed to behave more like a locally installed app. However, if you are going to use the dblclick
event, ensure the user knows to double click on items; that's not a common task on a web page.
$('#target').dblclick(function() { alert('hello, world!'); });
Forms
dblclick
is raised when the user double clicks on an element. The dblclick
event can be helpful when creating an application that is designed to behave more like a locally installed app. However, if you are going to use the dblclick
event, ensure the user knows to double click on items; that's not a common task on a web page. $('#target').dblclick(function() { alert('hello, world!'); });
blur
The blur
event is raised when a form element loses what's known as focus. This simply means the user has clicked elsewhere on the page or has tabbed away from the form control they were on. blur
is often used for validation, as you know the user has left the form field.
While this was originally designed for input
fields, many modern browsers allow the blur
event to be raised for any element type.
To register a handler with the blur
event, you can simply call the blur
function:
$('#target').blur(function() {
// retrieve the value using val
var value = $('#target').val();
alert(value);
})
blur
event is raised when a form element loses what's known as focus. This simply means the user has clicked elsewhere on the page or has tabbed away from the form control they were on. blur
is often used for validation, as you know the user has left the form field.input
fields, many modern browsers allow the blur
event to be raised for any element type.blur
event, you can simply call the blur
function:$('#target').blur(function() {
// retrieve the value using val
var value = $('#target').val();
alert(value);
})
change
The change
event is raised whenever an element is modified. However, the change
event is limited to input
, textarea
and select
elements only.
Besides just validation, the change
event can be used to create interfaces such as cascading dropdown lists. If the list of available values for one dropdown list depends on the selected value of another, change
is perfect for that. You would register the event handler on the parent, and when it changes update the child dropdown list.
The CodePen below provides a simple demonstration of cascading dropdown lists. When you select an option on the left, named parent
, it will create a custom set of options for the dropdown list on the right, named child
based on the selected value.
In the event handler, the logic first calls val
on parent
to retrieve the selected value. Then empty
is called on child
to clear out all of the options in the second dropdown. Two append
calls are made on child
to add the new options. Note the option
elements are built by simply using the option
tag and adding in a number (1 and 2) followed by the selected value.
Note: We will cover val
, parent
, empty
and append
later in this module. I just wanted to give you a functional demonstration of change
.
change
event is raised whenever an element is modified. However, the change
event is limited to input
, textarea
and select
elements only.change
event can be used to create interfaces such as cascading dropdown lists. If the list of available values for one dropdown list depends on the selected value of another, change
is perfect for that. You would register the event handler on the parent, and when it changes update the child dropdown list.parent
, it will create a custom set of options for the dropdown list on the right, named child
based on the selected value.val
on parent
to retrieve the selected value. Then empty
is called on child
to clear out all of the options in the second dropdown. Two append
calls are made on child
to add the new options. Note the option
elements are built by simply using the option
tag and adding in a number (1 and 2) followed by the selected value.val
, parent
, empty
and append
later in this module. I just wanted to give you a functional demonstration of change
.focus
focus
is essentially the opposite of blur
. focus
is raised when the user clicks, taps, or tabs into a particular control, typically because they want to change its value. You can use focus
to provide inline help for a form, such as letting the user know what format you expect for a phone number. This is demonstrated below.
One thing to note is you have the ability to "chain" registrations and other calls when using jQuery. Many jQuery functions return the object you originally accessed (the element with the id phone
below). As a result, you can simply call blur
right after callling focus
.
<!-- sample HTML -->
<div>
<label for="phone">Phone</label>
<input type="text" id="phone" />
<span id="phone-help"></span>
</div>
// sample JavaScript
$('#phone').focus(function() {
// Control has focus. Display help
$('#phone-help').text('Please enter your phone number as all digits');
}).blur(function() {
// Control lost focus. Clear help
$('#phone-help').text('');
});
Mouse movements
focus
is essentially the opposite of blur
. focus
is raised when the user clicks, taps, or tabs into a particular control, typically because they want to change its value. You can use focus
to provide inline help for a form, such as letting the user know what format you expect for a phone number. This is demonstrated below.phone
below). As a result, you can simply call blur
right after callling focus
.<!-- sample HTML -->
<div>
<label for="phone">Phone</label>
<input type="text" id="phone" />
<span id="phone-help"></span>
</div>
// sample JavaScript
$('#phone').focus(function() {
// Control has focus. Display help
$('#phone-help').text('Please enter your phone number as all digits');
}).blur(function() {
// Control lost focus. Clear help
$('#phone-help').text('');
});
mouseenter and mouseleave
mouseenter
is raised whenever the user moves their mouse over an element, and mouseleave
is raised when the user moves their mouse away from an element. You might use this to provide a tooltip or other contextual information.<!-- sample HTML -->
<div>
<span id="target">Basic data</span>
<span id="target-help"></span>
</div>
$('#target').mouseenter(function() {
$('#target-help').text('More data');
}).mouseleave(function() {
$('#target-help').text('');
});
hover
The
hover
event is logically equivalent to both the mouseenter
and mouseleave
events. What makes hover
special is you can actually register two event handlers in one call. The first parameter hover
accepts is for mouseenter
, or when the hover begins, and the second parameter is for mouseout
.
The code below is syntactically equivalent to the sample above.
$('#target').hover(function() {
// mouseenter
$('#target-help').text('More data');
}, function() {
// mouseleave
$('#target-help').text('');
});
No comments:
Post a Comment