HTML and CSS Reference
In-Depth Information
Handling DOM events
The DOM provides a large number of built-in events. The most common events used on a
more day-to-day basis are covered in this section. The DOM provides these events via the
JavaScript API. Functions can be specified as event listeners, and custom behavior can be
implemented onto webpages based on the event occurring. These events apply to most DOM
elements.
Change events
A change event occurs when the value associated with an element changes. This most
commonly occurs in input elements such as text-based inputs and others such as the range
element. An example of the change event in action is shown here:
<script>
window.onload = function () {
document.getElementById("aRange").addEventListener("change", rangeChangeEvent);
}
function rangeChangeEvent() {
document.getElementById("rangeValue").innerText = this.value;
}
</script>
<body>
<input id="aRange" type="range" max="200" min="0" value="0"/>
<div id="rangeValue"></div>
</body>
In this example, as the range slider control changes with the mouse dragging it from one
side to the other, the div displays the value of the slider bar.
EXAM TIP
This example uses the this keyword. In this context, the this keyword provides a direct
reference to the element that created the event. In this way, this provides shortcut access
to the element rather than gets a reference via one of the document search methods.
With the text input control, the same type of code can be processed:
document.getElementById("aText").addEventListener("change", rangeChangeEvent);
<body>
<input id="aRange" type="range" max="200" min="0" value="0"/>
<input id="aText" type="text"/>
<div id="rangeValue"></div>
</body>
Now when the text value of the text box changes, the div shows the value. The text box
change event is raised when the cursor leaves the text box, not as each character is typed.
 
 
 
Search WWH ::




Custom Search