Page 260 - Web_Application_v2.0_C12_Fb
P. 260
Thus, an event is defined as a change in an object’s state. There are a number of events in HTML that show
when a user or browser performs a certain action. JavaScript responds to these events when JS code is
embedded in HTML and permits execution. The act of responding to events is known as event handling. As a
result, JavaScript uses event handlers to handle HTML events.
Developers can use these events to run JavaScript coded replies that, among other things, cause buttons to
close windows, users to see messages, data to be validated, and just about any other reaction imaginable.
Events are a component of the Document Object Model (DOM) Level 3 and are present in every HTML
element. These events can be used to execute JavaScript code. Some examples are as follows:
Event Performed Event Handler Description
click onclick When mouse clicks on an element
mouseover onmouseover When the mouse cursor approaches over the element
mouseout onmouseout When the mouse cursor exits an element
mousemove onmousemove When any mouse movement takes place
load onload When the browser has finished loading the page
unload onunload The browser unloads the current webpage when the
visitor exits.
submit onsubmit The user submits the form
focus onfocus When an element gets selected or user concentrates on
that element
change onchange Triggers when a user modifies the value of an input
element and then clicks outside the input field.
keydown onkeydown Fires when any key is pressed while the input field is
focused.
Let us see few examples of event handling through JavaScript code.
Example 65: To demonstrate the use of onclick event
<!DOCTYPE HTML>
<HTML>
<HEAD>
<TITLE>JavaScript onclick</TITLE>
</HEAD>
<SCRIPT>
function showMessage() {
alert("Button clicked!");
}
</SCRIPT>
</HEAD>
<BODY>
<button onclick="showMessage()">Click Me</button>
</BODY>
</HTML>
258 Touchpad Web Applications (Ver. 2.0)-XII

