Java learning notes - browser event model

Posted by Nexus10 on Fri, 14 Jan 2022 13:32:58 +0100


Events are actions or events that occur in the system during programming. After the system responds to events, you can respond to events in some way if necessary.
In the Web, events are triggered in the browser window and are usually bound to a specific part of the window - possibly an element, a series of elements, HTML code loaded into the window, or the entire browser window.

Event flow

Event flow describes the order in which events are accepted in a page.

The event flow specified by "DOM2 level event" includes three stages: event capture stage, target stage and event bubble stage. - JavaScript advanced programming

According to the W3C model, events are first captured by the target element and then bubble up—— MVC based JavaScript Web rich application development

Event capture

The event is triggered from the top-level parent node, propagated from outside to inside, and ends with the trigger event originTarget.

Event Bubbling

The event is triggered from the inner originTarget node, propagates from the inside to the outside, and bubbles level by level until the end of the top-level node.

Note: not all events support event bubbling. Bubble, focus, load, unload, mouseenter, mouseleave and custom events do not support event bubbling.

Prevent event propagation

  • e.stopPropagation(): what you often hear may be to prevent bubbling. In fact, this method can not only prevent bubbling, but also prevent the propagation of capture phase.
  • e.stopImmediatePropagation(): prevents other event listeners listening to the same event from being called. If multiple event listeners are attached to the same event type of the same element, when this event is triggered, they are called in the order in which they are added. If stopImmediatePropagation() is executed in one of the event listeners, none of the remaining event listeners will be called.

Block event default behavior

e.preventDefault() can prevent the default behavior of events. The default behavior refers to: clicking the a tag to jump to other pages, dragging a picture to the browser will open automatically, clicking the submit button of the form will submit the form, etc. sometimes we don't want these things to happen, so we need to prevent the default behavior.

be careful:

  1. Only events with the cancelable property of true can use the preventDefault() method to cancel their default behavior
  2. If you want to stop bubbling and block the default behavior, you can directly return false

Event handler (event listener)

A function or block of code used to respond to an event

Event handler HTML properties (inline event handler)

The attribute value is the JavaScript code to run when the event occurs

<input id="btn" type="button" onclick="handleClick(this.value)" value="hello"/>
    function handleClick(value){
        console.log('this', this); // window
        console.log(value);  // hello
        console.log(this.value);  // undefined

When specified in this way, a function encapsulating the value of the element attribute is created. This function has a local variable event (i.e. event object). Through the event variable, you can directly access the event object. You don't need to define it yourself or read it from the parameter list of the function (after testing, you don't need to read it from the parameter list of the function in chrome, and IE 11, but you need it in fireFox). Inside this function, the value of this is equal to the target element of the event—— JavaScript advanced programming

The above paragraph can be understood as: when specifying the event handler through the html attribute, wrap a layer of functions outside the specified handler function, and then assign the new function to BTN Onclick (see DOM0 level event handler), so that this in the new function points to the event target element. However, inside the specific event handler function handler, since there is no specific calling object, in the non strict mode, its internal this points to window

DOM0 level event handler

var btn = document.getElementById("btn");
btn.onclick = function() {
    alert(; // btn

DOM2 level event handler

The main methods are addEventListener and removeEventListener. They both accept three parameters: the name of the event to be processed, the event handling function, and a Boolean value (indicating whether event capture is enabled). The main advantage of using them is that multiple event handlers can be added.

Note: if the listening function is an anonymous function without any reference to it, the listening cannot be removed without destroying this element.

Ie event handler (IE7, IE8)

IE implements attachEvent() and detachEvent(). Both methods accept two parameters: the event handler name and the event handler function.

  • When using these two functions, the event handler runs in the global scope, so this points to window
  • These event handlers do not run by adding them, but are triggered in the reverse order

Cross browser event handlers

function addHandler(target, eventType, handler) {

    if (target.addEventListener) { // DOM2 Events
        target.addEventListener(eventType, handler, false);
    } else if (target.attachEvent) { // IE
        target.attachEvent('on' + eventType, handler);
    } else {
        target['on' + eventType] = handler;

function removeHandler(target, eventType, handler) {

    if (target.removeEventListener) {
        target.removeEventListener(eventType, handler, false);
    } else if (target.detachEvent) { 
        target.detachEvent('on' + eventType, handler);
    } else {
        target['on' + eventType] = null;

// Block events (mainly event bubbling, because IE does not support event capture)
function stopPropagation(e) {
    if (e.stopPropagation) {
        e.stopPropagation(); // Standard w3c
    } else {
        e.cancelBubble = true; // IE

// Cancels the default behavior for events
function preventDefault(e) {
    if (e.preventDefault) {
        e.preventDefault(); // Standard w3c
    } else {
        e.returnValue = false; // IE

Event delegation

Generally speaking, it is to delegate the function of one element in response to events (click, keydown, etc.) to another element.
Usually, the events of one or a group of elements are delegated to its parent layer or more outer elements. The outer elements are the ones that really bind events. When the event responds to the elements that need to be bound, it will be triggered through the event bubble mechanism.

Custom event

Non IE browser

  • Mode 1

    // Create an event. The parameter is event type
    var event = new Event('Event'); 
    // Initialization event
    // initEvent(type: string, bubbles?: boolean, cancelable?: boolean): void;
    event.initEvent('build', true, true); 
    elem.addEventListener('build', function(e) {
      // do something
    }, false);
    // Trigger event
  • Mode II
    The constructor of Event is defined as new(type: string, eventInitDict?: EventInit): Event;
    The definition of EventInit is:

    interface EventInit {
      bubbles?: boolean; // Bubble or not, false by default
      cancelable?: boolean; // Can I cancel? The default is false
      composed?: boolean; //Whether the listener will be triggered outside the shadow DOM root node. The default is false
    // Create and initialize events
    var event = new Event('build', {
      bubbles: true,
      cancelable: true
    elem.addEventListener('build', function(e) {
      // do something
    }, false);
    // Trigger event

IE8 and earlier browsers

var event = document.createEventObject(); // No parameters are accepted

// Assign a value to the property of event

elem.fireEvent('onclick', event); // Trigger event

When calling the fireEvent() method, the srclelement and type attributes will be automatically added to the event object; Other attributes must be added manually.

Event object

Event objects are divided into event objects in DOM and event objects in IE for compatibility. The properties and methods of event objects include the properties and methods of these two event objects.

Properties / methods of event objects in DOM

  • bubbles: boolean indicates whether the event is bubbling
  • cancelable: boolean indicates whether the default behavior of the event can be canceled
  • Composed: will Boolean trigger the listener outside the shadow DOM root node
  • Currenttarget: the element of the EventTarget that is currently calling the event handler
  • Defaultprevented: a Boolean of true indicates that the preventDefault() method has been called
  • eventPhase: number the stage in which the event handler is called: 1 indicates the capture stage, 2 indicates "on target", and 3 indicates the bubbling stage
  • isTrusted: boolean indicates whether the event is generated by the browser
  • Target: the target of the EventTarget event
  • initEvent(type: string, bubbles?: boolean, cancelable?: boolean): void;
  • preventDefault(): void
  • stopImmediatePropagation(): void
  • stopPropagation(): void
  • type: string event type

Properties / methods of event objects in IE

  • Cancelbubble: the default value of Boolean is false, but set it to true to cancel event bubbling
  • ReturnValue: the default value of Boolean is true, but setting it to false can cancel the default behavior of the event
  • Srclelement: target of element event, corresponding to target
  • type: string event type (the type in IE is the same as the type in DOM)

Note: the difference between target and currentTarget

Topics: Javascript event