Understanding the Concept of Event Driven Web Programming
A typical script always follows a strict flow of actions. A follows B follows C follows D. However, the operation carried out within an event driven program will depend on the actions initiated by the program user. So, for example, these user actions may be to:
- load a web page
- click on a button
- move the mouse
- submit a form
The web application will behave differently according to the action carried out by its user. It is, therefore, worth spending a little time looking at some of these events in detail.
function button_click () alert ("You clicked me!");
The programmer can then add this function to a web page object (such as an input button) by using the object's onclick parameter:
input type=button value="Click Me" onclick="button_click();"
The web site user would now see a button which, when clicked, causes a simple message box to be displayed. However, the experienced programmer will realize that there is an obvious limitation to this technique. It only allows static function calls to be written. Likewise any variable sent to the functions will also have to be static. Fortunately, there is a simple solution.
function button_click_ip (text) alert (text);
This time the function requires an input (text) and it’s this input that will be displayed as the body of the message box. Undoubtedly, the input will be hard coded straight into the onclick parameter from the input button. However, this is rather limiting (and not really good practice). For that reason the function is associated with the input button in a different way. This time the onclick parameter is not set when the button is defined:
input type=button value=”And me!” id=button2
document.getElementById("button2").onclick = function () button_click_ip(this.value);;
The end result (as seen by the web site user) is the same but the web programmer has a flexible technique that can be used on any web page elements (such as select boxes and form submit buttons). This simple piece of web programming enables the application developer to create a web page that will respond to each and every action that their users may carry out.