Attaching Events
As we discussed briefly in the section Bunch SET methods, there are methods available to help you
easily and quickly fetch a node, or series of nodes, and attach event
handlers to the bunch object that is returned. These methods are the
query method, q()
, to fetch the
nodes, and the event attach method, on()
, to insert the
events:
//get node through the query method var bunch = dom.q("QUERY"); //attach event onto the returned bunch object bunch.on("EVENT", function(e){ ... }
In this example, we can see how to attach a click handler to a submit button to pop up an alert message:
var objSubmit = dom.q("#btnSubmit"); objSubmit.on("click", function(e){ alert("You have just clicked the button - you win a prize"); });
The click event is just one of many DOM events that are supported through the event attach method. If we explore the full list of available events shown in Table 8-12, we see that there are several user-initiated features that we can account for in our programs.
Table 8-12. DOM events supported through the event attach method
Event | Description |
---|---|
| The focus on the element has been lost. |
| The user has changed the value of an input, select, or |
| The user has clicked on the object with her mouse. |
| The user has clicked on the object twice with her mouse. |
| The user has pressed the Enter key while in a focused element. |
| The user has pressed the Escape key while in a focused element. |
| The user has given an object focus. |
|
Get Programming Social Applications now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.