California Ajax Solutions Team

www.CalAST.com

Event handling

Of course, this brings up the issue of how the browser knows what the user has done so it can respond in an appropriate way, and Ajax is closely integrated with the concept of event handling. An event listener is a function that is associated with some event in the system. The most common of these events is called onclick and, as you would expect, it is invoked when the user clicks on something. When that happens, the browser looks to see if there is a JavaScript function associated with the DOM element (a button, for example) that the user clicked on. If so, that function is called. That's how the button on the previous page works. There are a number of other events, like onchange (when the user selects from a list or modifies a text box), many events associated with the mouse being over or not over an element, and so on. All of these can have event listeners, but it is not necessary to provide them unless you want a specific behavior. If there is no event listener, the browser simply doesn't do anything interesting.

So in our example, when the user changed the currently selected car brand to Ford, an onchange event fired, and the onchange event listener for the brand drop-down list was called. Event listeners are either passed the object on which the event occurred or no arguments at all. They are instead written to obtain all the information they need from standard JavaScript functions. For example, if you gave the drop-down list for brands the name brands by coding <select id="brands">, then the event listener can find it by calling a function as getElementById("brands"), which will return the DOM node for the drop-down list (called a SELECT in HTML). You can then look through it to find out which brand was chosen. Once you know this, you can obtain a list of models for that brand from the server and use it to replace the current list of models with something more appropriate, based on what the user chose. How this happens gets into the heart of Ajax and how this technique works.

Next

Event listener demo