HTML DOM Events

Events encompass specific actions executed either by users or the web browser itself. These actions can transpire across any section of a document, stemming from either user interactions or browser processes. Typically, events are coupled with functions, and these functions remain dormant until the corresponding event unfolds. To amplify webpage interactivity, scripting must enable document content access and the detection of user interactions, thereby promoting a dynamic and responsive user experience.

Dom Event Handlers

The Document Object Model (DOM) event mechanism facilitates event handling and furnishes event-related information to scripts. It establishes a standardized framework for discerning the event's source, type, occurrence time, and position in the document. Two prevalent approaches for event handling are the general addEventListener() method and a range of specific on-event handlers. These on-event handlers constitute a collection of properties embedded within DOM elements, which dictate the element's response to events. These event handlers possess names that initiate with "on," such as "onclick" for the click event and "onfocus" for the focus event, facilitating comprehensive event management within the DOM structure.

A crucial consideration is that each object can host only a single on-event handler for a specific event. This limitation underscores why addEventListener() is frequently the preferred approach for event notification. This method is particularly advantageous when aiming to implement multiple event handlers autonomously, even for the same event and/or on the same element, without encountering conflicts or overwriting existing handlers. This flexibility makes addEventListener() the preferred choice for managing diverse event scenarios with precision and independence.

Inline HTML Attributes

Numerous methods exist for attaching event handlers. The simplest approach involves adding dedicated attributes to HTML tags. Inline events are linked to elements via attributes commencing with the "on" prefix. It's important to recognize that not all event types are universally applicable to all elements, as certain events might be exclusive to specific elements. Here is a list of some common HTML events:

  1. onchange: An HTML element has been changed.

  2. onclick: The user clicks an HTML element.

  3. onmouseover: The user hovers the mouse over an HTML element.

  4. onmouseout: The user moves the mouse away from an HTML element.

  5. onkeydown: The user pushes a keyboard key down.

  6. onload: The browser has finished loading the page.

For example, in order to execute some JavaScript when a heading(h1) is clicked, you can use the following:

<!DOCTYPE html> <html> <body> <h1 id="Heading" onclick="alert('You Clicked...!!')">Click Here</h1> </body> </html>
run this source code Browser View

Click Here

When the user clicks on "Heading" text on webpage, you can see the click event fires and the string of JavaScript code contained in the onclick attribute is executed.

Function Call

When events are triggered, if you intend to execute a sequence of code, you can consolidate the code within a function and subsequently invoke the function to initiate its execution. This approach streamlines the management and organization of code related to event handling, promoting modularity and maintainability.

<!DOCTYPE html> <html> <body> <script type="text/javascript"> function findSquare(i) { alert("Square of a given number is : " + (i*i)); } </script> <input type="button" value="Click Me" onclick="findSquare (5)" /> </body> </html>
run this source code Browser View

Event Listener

A function that is invoked in response to an event is termed an event handler. This event handler can then be attached to an element, associating it with a specific event. During user interactions with an element, the browser checks whether an event handler is registered for the particular event type pertaining to that element. While events like click and mousemove are universally supported across browsers and devices, mouseover events aren't triggered on most smartphones due to their inability to detect finger hovering. However, certain smartphones are incorporating sensors to enable mouseover detection in the future. The ensuing example illustrates how to capture various event types using JavaScript.

<!DOCTYPE html> <html> <body> <h1 id="h4" onmouseover="handle(event)">Mouse Over Here !!</h1> <h1 id="h2" onclick="handle(event)">Click Here !!</h1> <h1 id="h3" ondblclick="handle(event)">Double Click Here !!</h1> <script type="text/javascript"> function handle(e) { alert(e.type); } </script> </body> </html>
run this source code Browser View

Mouse Over Here !!

Click Here !!

Double Click Here !!

Adding the addEventListener Method

An additional technique for incorporating event handlers involves utilizing the addEventListener method. The EventTarget.addEventListener() method facilitates the inclusion of a designated EventListener-compatible object into the collection of event listeners associated with the specified event type on the respective EventTarget to which the method is applied.

document.addEventListener('click', myfunction, false);
example
<!DOCTYPE html> <html> <body> <button id="eventBtn">Try it</button> <p id="display"></p> <script> document.getElementById("eventBtn").addEventListener("click", myFunction); function myFunction() { document.getElementById("display").innerHTML = "Its Worked !!"; } </script> </body> </html>
run this source code Browser View

More Event Models

The Document Object Model standard provides a large number of events and they can be grouped into six major categories:

  1. MouseEvents : click, mousedown, mouseup, mousemove, etc.

  2. KeyboardEvents : keypress, keydown, and keyup.

  3. HTMLEvents : load, error, resize, scroll, etc.

  4. Form events : select, change, submit, reset, focus, etc.

  5. UIEvents : focusin and focusout.

  6. MutationEvents : DOMNodeInserted, DOMAttrModified, etc.

Conclusion

HTML DOM events enable the scripting of dynamic interactions on web pages, triggered by user actions or browser processes. Developers can employ techniques like inline event attributes or the addEventListener() method to associate event handlers with specific elements, facilitating responsive behaviors and enhancing user experiences.