JavaScript/Handling Events

So far, the shown JS programs start automatically when the HTML page is loaded. This kept everything small, simple, and straightforward.

Now we want to introduce the mechanism of starting a program intentionally at specific points in time. When a user types in some content, it may be necessary to evaluate it; when a user clicks a button, it may be necessary to start a complex action like a database query. The actions (validation, DB query) will be handled in a JS function, and some HTML code will initiate the call to such JS functions. To understand how it works, we must learn about events. In a later chapter, we will explain events in detail.

Assume a user clicks on a button. This generates an onclick event. The occurrence of such an event is declaratively combined with a call to a named JS function. The browser calls this JS function. The JS function runs.

The complete HTML with its embedded JS reads:


 * In contrast to the previous examples, nothing happens when the page is loaded. This results from the fact that the  command is embedded in the JS function  . This function is only defined but not started.
 * The HTML element  has an attribute   with a value.
 * When the button is clicked, an onclick event occurs. The event is bound to the button.
 * The browser handles the event. He notices that a function with the given name shall run.
 * The browser searches for the function in all available JS scripts (please notice that this name as well as all JS code is case-sensitive!).
 * After finding the function with exactly this name in the  part, the browser starts the function.
 * The function executes and shows the message.

In essence, the JS function with its message-showing behavior will run whenever the user clicks on the button.

Second Example
This example offers the possibility to change the background color of some HTML elements. It uses 3 buttons, 2 JS functions, and 1 event type (onclick; there are many other types). Furthermore, it introduces the concept of an element id.

What are the differences to the first example?
 * There are 3 buttons. The first two are associated with a JS function; the third is not.
 * The  and the second   elements contain an attribute  . This assigns an identifier to them. He can be used in JS to locate them.
 * The  element contains two functions with different names.
 * When you click on one of the buttons, the associated JS function is called. Because the third button has no associated JS function, nothing happens there.
 * In JS, the code part  locates the element with this ID. The code part   modifies the background color of this element. Please ignore that the two parts are written in separate lines. This is only for better reading of the source code on small devices. You can link the two lines together.
 * The  function executes two statements and changes the background color of the body and of itself.