SoFunction
Updated on 2025-03-01

Analysis of five ways to specify handlers for events in JavaScript

This article describes five ways to specify handlers for events in JavaScript. Share it for your reference, as follows:

The interaction between JavaScript and HTML is achieved through events.

IE9, Firefox, Opera, Sarifi, and Chrome have all implemented the core part of the DOM2-level event module, and IE8 is the last major browser to still use its proprietary event system.

Event flow:

Event streams describe the order of events being accepted from the page, but IE and Netscape propose the completely opposite concept of event streams. IE's event stream is an event bubble stream, while Netscape's event stream is an event capture stream.

1) Event bubbles

The event starts by the most specific element (the node with the deepest nesting level in the document, and then propagates upward step by step to the less specific node (the document).

Events that do not support bubbles:blurfocusloadunload

2) Event Capture

A less specific node should receive the event earlier, while the most specific node should receive the event at the end. The purpose of event capture is to capture the event before it reaches the predetermined target.

Although IE9, Safari, Chrome, Firefox, and Opera all support event capture and event bubbles, IE8 and its earlier versions only support event bubbles and do not support event capture, so. It is recommended to use event bubbles and use event capture when there are special needs.

DOM event stream:

The event flow specified by the DOM2 level event includes three stages: the event capture stage, the target stage and the event bubble stage. In fact, the predetermined target does not receive an event during the event capture phase, and the event occurs on the predetermined target during the target phase. In event processing, being in the target stage is regarded as part of the event bubble stage. However, even if the "DOM2 level event" specification explicitly requires that the capture stage will not involve the event target, IE9, Safari, Chrome, Firefox, and Opera9.5 and later will trigger events on the event object during the capture stage, resulting in two opportunities to operate events on the target object.

IE9, Firefox, Opera, Sarifi, and Chrome all support DOM event streams, while IE8 and its earlier versions do not support DOM event streams.

Event handler:

An event is a certain action performed by the user or browser itself, and the function that responds to an event is an event handler (or event listener), and the name of the event handler begins with "on".

There are five types of event handler methods in JavaScript:

1) HTML event handler

Each event can be specified using an HTML feature with the same name as the corresponding event handler. The value of the feature can be executable JavaScript code or a function. There is a local variable event in the function, through which event variables can access the event object; inside the function, this value is equal to the target element of the event.

Several disadvantages of specifying event handlers in HTML:

① Time difference problem: The user may trigger the corresponding event as soon as the HTML element appears on the page, but the event handler at that time may not have the execution conditions, such as the user triggers the event before parsing the event handler function. To this end, many HTML event handlers are encapsulated in a try-catch block to catch errors in time so as not to be seen by the user.

② The scope chain of the extended event handler will lead to different results in different browsers. Different JavaScript engines follow slightly different identifier resolution rules, and there is a high possibility that an error occurs when accessing non-qualified object members.

③HTML code is closely coupled with JavaScript code. To change the event handler, you need to change the HTML code and JavaScript code.

2) DOM0 level event handler

The traditional way of specifying event handlers through JavaScript is assigned to an event handler attribute. The event handler specified using the DOM0 level method is considered as a method of an element, so this references the current element.

Advantages of DOM0-level event handlers:

①Simple;

② Cross-browser

The event handler specified by the DOM0 level method can be deleted by setting the value of the event handler to null.

3) DOM2 level event handler

DOM2-level events define two methods for specifying and deleting an event handler:addEventListener()andremoveEventListener(), they all receive 3 parameters: the event name to be processed, the function as the event handler, and a boolean value (true means calling the event handler in the capture stage, false means calling the event handler in the bubble stage).

Advantages of DOM2-level event handler:

Multiple event handlers can be added, and they are fired in the order in which they are added.

passaddEventListener()The added event handler can only be usedremoveEventListener()to remove, but the parameters passed in when removing are required to be the same as those used when adding the event handler, soaddEventListener()The added anonymous function will not be removed and needs to be givenremoveEventListener()IncomingaddEventListener()The functions named in the program can be removed normally.

4) IE event handler

IE events define two methods:attachEvent()anddetachEvent(), they all receive 2 parameters: the event name to be processed, and the function as an event handler. Since IE8 and its earlier versions only support event bubbles, event handlers added through attachEvent() will be added to the bubble phase.

Note: Through IEattachEvent()The added event handler name starts with "on" and through the DOMaddEventListener()The added name is not.

Use in IEattachEvent()The main differences from using the DOM0-level method:

Event handlers have different scopes. Using attachEvent() in IE, the event handler will run in the global scope, so this is equal to window; while using the DOM0-level method, the event handler will run in the scope of the element to which it belongs.

Use in IEattachEvent()Differences from using DOM2-level method:

The execution order of adding multiple event handlers is different. Using attachEvent() in IE, you can add multiple event handlers, which will be triggered in the reverse order in which they are added; use in DOMaddEventListener(), multiple event handlers can be added, but they will be fired in the order in which they are added.

passattachEvent()The added event handler can only be useddetachEvent()to remove, but the parameters passed in when removing are required to be the same as those used when adding the event handler, soattachEvent()The added anonymous function will not be removed and needs to be givendetachEvent()IncomingattachEvent()The functions named in the program can be removed normally.

5) Cross-browser event handler

To ensure that the code of the event handler runs consistently in most browsers, just focus on the bubbling phase.

Depending on the situation, use the DOM2 level method, IE method, and DOM0 level method to add and remove events.addHandler()andremoveHandler()The method belongs toEventUtilObject.

① First check whether the incoming element has a DOM2-level method (the third parameter passed isfalseto indicate the bubbling stage);

② Method to detect whether the incoming element exists in IE;

③ Finally, detect whether the incoming element has a DOM0-level method (using square bracket syntax to specify the attribute name as the event handler).

var EventUtil = {
  addHandler:function(element, type, handler) {
    if ()
      (type, handler, false);
    else if ()
      ("on" + type, handler);
    else
      element["on" + type] = handler;
  },
  removeHandler:function(element, type, handler) {
    if ()
      (type, handler, false);
    else if ()
      (“on” + type, handler);
    else
      element["on" + type] = null;
  }
}

PS:For instructions on javascript events, please refer to this siteA complete list of javascript events and functionshttp://tools./table/javascript_event

For more information about JavaScript, readers who are interested in reading this site's special topic:A complete collection of operations and techniques related to JavaScript events》、《Summary of JavaScript page element operation skills》、《Summary of JavaScript DOM skills》、《Summary of JavaScript search algorithm skills》、《Summary of JavaScript data structure and algorithm techniques》、《JavaScript traversal algorithm and skills summary"and"Summary of JavaScript Errors and Debugging Skills

I hope this article will be helpful to everyone's JavaScript programming.