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
There are two instances in which the event handlers for these events may be triggered:
The user has performed an action that has triggered the event.
The developer has programmatically triggered the event without user interaction.
If the developer triggers the events without user interaction, the browser’s default action will not be triggered. For the default browser action to be triggered when the event is triggered, the user must be the event initiator.
When the event is triggered, the function that is associated with the event will be triggered:
objSubmit.on("click", function(e){ ... }
The function that is triggered will contain one argument, the event object. This event object can contain a number of properties that allow you to determine information about the event programmatically once it has been triggered. This object will help you to modularize your event handler so that you have a single handler for all events that uses the information from the event object to determine what action it should take.
Table 8-13 lists all of the properties that may be set within an event object.
Table 8-13. Event object properties
As you can see, there are many event features available for us to work with. This extensive list will help us to build highly targeted applications and sites that allow specific handling for user events and actions.
18.189.180.43