Listen Up! An Overview of Event Handling in Javascript
An HTML event is a pretty straightforward concept –– it is something that happens to an HTML element. An HTML event can either be something the browser does or something the user does. For example, an HTML event can be when an HTML page has finished loading, when and input field has been changed or submitted, or when an HTML element has been clicked. Javascript can react to these HTML events and execute some kind of code as a result, which can greatly impact the way a user interacts with a web application and the way a web application responds to a user. This blog contains introductions to and brief overviews of various concepts related to event listening and event handling in Javascript.
HTML Event Handler Attributes
Event handler attributes can be added directly to an HTML element. These attributes are added in the following manner:
In the screenshot above, “onclick” is the event. The javascript code assigned to the event would execute whenever the event occurs on the particular element. As the name of the event implies, the Javascript code in the above example would run whenever a user clicks on the HTML element. Javascript code can be passed directly into the HTML element inside quotation marks, however, Javascript code can often be long and take up several lines. For this reason, it is more common to see an event attribute calling a function that has been defined elsewhere.
There are a few common event handler attributes that are embedded directly into an HTML element. In addition to “onclick”, some of the most common event handler attributes are:
- onmouseover ~ the user moves the mouse over an HTML element
- onmouseout ~ the user moves the mouse away from an HTML element
- onchange ~ an HTML element has been changed
- onload ~ the browser has finished loading the page
For more event handler attributes, see: https://www.w3schools.com/jsref/dom_obj_event.asp
Event Listener Method
Another way to attach an event handler to an element is through the addEventListener() method. This method attaches an event handler to an element without overwriting any existing event handlers. This method can also be used to add multiple event handlers to a particular element, even event handlers of the same type (i.e. — multiple “click” handlers on one element). The addEventListener() method can also be used to add event listeners to any HTML DOM object. This includes HTML elements, the HTML document, and the window object.
The syntax for the addEventListener() method is as follows:
The first parameter of the method is the event in the form of a string (i.e. — “click” or “submit”). When assigning an event handler through the addEventListener() method, the “on” prefix is omitted. For example, “onclick” becomes “click” and “onmouseover” becomes “mouseover”, etc. The second parameter of the method is a function that should be called whenever the event occurs. The third parameter is an optional boolean value specifying whether to use event bubbling or event capturing.
Bubbling and capturing are the two types of event propagation in the HTML DOM. When multiple elements are listening for the same event, event propagation defines the order in which the event occurs. For example, if a paragraph (<p>) element is nested inside a division (<div>) element, and both elements have a “click” event listener, bubbling and capturing can determine which element’s “click” event should be handled first.
In bubbling, the innermost element’s event is handled first and the outermost element’s event is handled last. In the example above, the <p> element’s event would be handled first and the <div> element’s event would be handled second.
In capturing, the outermost element’s event is handled first and the innermost element’s even is handled last. So, in the example above, the <div> element’s event would be handled first and the <p> element’s event would be handled second.
The “useCapture” boolean can be used to specify the propagation type. The default value is false, which means that bubbling propagation would be used unless the “useCapture” attribute is explicitly set to “true”.
Any event handler that has been attached using the addEventListener() method can be removed using the removeEventListener() method. This method should take in (as parameters) the same event and function as the addEventListener() method that is being removed. This method is particularly useful if an event handler should only be available until some action has been performed.
Common Event Handlers
The following sections will cover some of the most common event handlers along with some practical uses for the various categories. This list is in no way exhaustive; a link to a more comprehensive list will be at the end of this section.
DOMContentLoaded
The DOMContentLoaded event happens when the initial HTML document has been fully loaded and parsed. This means that the event happens without waiting for stylesheets, images, and subframes to finish loading.
There is a different event handler, load, that should only be used to detect a fully-loaded page. This means that the event happens when the resource and its dependent resources have been loaded.
Keyboard Events
- keydown ~ this event happens when any key is pressed
- keyup ~ this event happens when any key is released
- keypress ~this event happens when any key except non-character keys (Shift, Fn, CapsLock, Ctrl, Alt, etc.) is in a pressed position position
An example case for using a keyboard event listener would be a search bar that filters the displayed content of the page. As the user types in each letter of their search, a keyboard event listener can re-run the filtering function using their input to immediately alter the displayed content.
Mouse Events
- mouseenter ~ this event happens when a pointing device is moved onto the element that has a listener attached
- mouseover ~ this event happens when a pointing device is moved onto an element that has a listener attached or onto one of its children
- mouseleave ~ this event happens when a pointing device is moved off the element that has a listener attached
- mouseout ~ this event happens when a pointing device is moved off an element that has a listener attached or off one of its children
- click ~ this event happens when a pointing device button has been pressed and released on an element (this currently applies to any button on the pointing device, but will soon be changed to the primary button only)
- dblclick ~ this event happens when a pointing device button is clicked twice on an element
An example case for using a mouse event listener would be altering the style of an element as a user performs different actions. For example, the color of an element can change when a user moves the pointer onto the element, and then revert back when the pointing moves off of the element.
CSS Events
For those interested in creating animated web pages or games using Javascript, the following event handlers may come in handy:
- animationstart ~ this event happens when a CSS animation has started
- animationend ~ this event happens when a CSS animation has completed
- animationiteration ~ this event happens when a CSS animation is repeated
- transitionstart ~this event happens when a CSS transition has actually started (after any delay)
- transitionrun ~ this event happens when a CSS transition has started running (before any delay)
- transitioncancel ~this event happens when a CSS transition has been cancelled
- transitionend ~ this event happens when a CSS transition has completed
For a more comprehensive list of common event handlers, see Most Common Categories at: https://developer.mozilla.org/en-US/docs/Web/Events