Handling Javascript DOM Events



The DOM provides a large number of built-in 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.

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.

The code below demonstrates the change event:

<body>
<div id="#div1">
   <h4>SHOW THE VALUE - CHANGE EVENT</h4>
       <input id="aRange" type="range" max="200" min="0" value="0" />
       <div id="rangeValue"></div>
</div><br />
<div id="#div1"> </div>
<!-- CHANGE EVENT  -->
<script type="text/javascript">
    window.onload = function () {
        document.getElementById("aRange").addEventListener("change", rangeChangeEvent);
    }
    function rangeChangeEvent() {
        document.getElementById("rangeValue").innerText =
            ("The Value current is: " + this.value);
    }
</script>
</body>

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.

Focus events

Focus events occur when an element receives or loses the focus. The following table lists the available events related to focus.

Event Description
focus Raised when the element receives the focus
blur Raised when the element loses the focus
focusin Raised just before an element receives the focus
focusout Raised just before an element loses the focus

The number of focus events provide very good flexibility in how the focus of any particular DOM element is handled with respect to the timing.

The blur event is commonly used to validate form fields. You can use the focus() method to set the focus to any element that causes the focus event hierarchy to occur.

The following code shows how to use the blur event:

<body>
<div id="#div2"> 
    <form>
        <h4>VALIDATING INPUT TYPE - FOCUS EVENTS</h4>
        <label for="firstname">Name : </label>
        <input type="text" id="firstNameText"><br />
        <div id="ruleViolation"></div>
    </form> 
</div><br />
<!-- Focus events --> 
<script type="text/javascript">
window.onload = function () {
    document.getElementById("firstNameText").focus();
    //enclosures FUNCTION
    document.getElementById("firstNameText").addEventListener("blur", function () {
        if (this.value.length < 5) {
            document.getElementById("ruleViolation").innerText =
            'First Name is required to be 5 letters.';
            document.getElementById("ruleViolation").style.color = 'red';
            this.focus();
        }
    });
}
</script>
</body>

Ads Right