Home Web Front-end JS Tutorial Detailed explanation of event flow and event handlers in JavaScript (graphic tutorial)

Detailed explanation of event flow and event handlers in JavaScript (graphic tutorial)

May 21, 2018 pm 01:47 PM
javascript js event

The event stream refers to the order in which events are received from the page, while the event handler handles the response to the event. Next, we will explain the event stream and event handler in JavaScript in detail.

Events Stream: There are two types. IE's is an event bubbling stream. The event is received from the most specific element at the beginning and propagated upwards to less specific nodes (Element -> Document). The opposite is Netscape's event capture stream.

DOM2-level events stipulate that the event flow includes three stages: event capture stage, target stage and event bubbling stage.

In most cases, event handlers are added to the bubbling phase of the event flow. An example of EventUtil:

var EventUtil = {
  addHandler: function(element, type, handler){
    if(element.addEventListener){
      element.addEventListener(type, handler, false);
    }else if(element.attachEvent){
      element.attachEvent('on' + type, handler); // IE8
    }else{
      element['on' + type] = handler;
    }
  },
  removeHandler: function(){...}
}
Copy after login

Let’s look at it in detail:

DOM0-level event handlerThe traditional way to specify an event handler through Javascript is to assign a function Give an event handler attribute.
Each element has its own event handler attributes, which are usually all lowercase, such as onclick. By setting the value of this property to a function, you can specify an event handler.

var btn = document.getElementById('myBtn');
// 添加事件处理程序
btn.onclick = function () {
  alert( this );//为DOM元素btn
};
// 移除事件处理程序
btn.onclick = null;
Copy after login

Advantages: 1. Simple 2. Cross-browser advantages
Disadvantages: Event handlers are not specified before the code is run, so these codes are located behind the buttons in the page, and there is a possibility of There is no response no matter how you click for a period of time, and the user experience becomes worse.

DOM2-level event handler defines two methods for handling the operations of specifying and removing event handlers: addEventListener() and removeEventListener(). Three parameters, 1. The name of the event to be processed. 2. A function as an event handler 3. A Boolean value. The last Boolean value is true, which means the event handler is called during the capture phase, and false, which means the event handler is called during the bubbling phase.

// 添加多个事件处理程序
var btn = document.getElementById('myBtn');
btn.addEventListener('click',function (){
  alert( this );// 为DOM元素btn
},false );
btn.addEventListener('click',function () {
  alert('Hello World');
},false);

// 移除事件处理程序
btn.removeEventListener('click',function () {
  // 匿名函数无法被移除,移除失败
},false);
  // 改写
  var handler = function () {
  alert(this.id);
  };
  btn.addEventListener('click',handler,false);
  // 再次移除事件处理程序
  btn.removeEventListener('click',handler,false);// 移除成功
Copy after login

These two event handlers will fire in the order in which they are added. In most cases, event handlers are added to the bubbling phase of the event flow, so as to maximize compatibility with various versions of browsers.

Advantages: One element can add multiple event handlers
Disadvantages: IE8 and below browsers do not support DOM2-level event handlers. (Including IE8)

IE event handler defines two methods, similar to the above: attachEvent(), detachEvent(). Both methods receive the same two parameters: event handler name and event handler function. Since IE8 and earlier browsers only support event bubbling, event handlers added through detachEvent() will be added to the bubbling phase.

var btn = document.getElementById('myBtn');
btn.attachEvent('onclick', function(){
  alert( this );// window
});
btn.attachEvent('onclick', funciton(){
  alert("HELLO, WORLD");
});
Copy after login

When the button is clicked, the firing order of these two event handlers is exactly the opposite of the above. Instead of triggering the event handlers in the order they were added, just the opposite.

Advantages: Multiple event handlers can be added to one element
Disadvantages: Only supports IE.

Cross-browser event handler

eg:

var EventUtil = {
  addHandler : function ( ele, type, handler ) {
    if ( ele.addEventListener ) {
      ele.addEventListener( type, handler, false );
    } else if ( ele.attachEvent ) {
      ele.attachEvent( 'on' + type, handler );
    } else {
      ele['on' + type] = handler
    }
  },
  removeHandler: function ( ele, type, handler ) {
    if ( ele.removeEventListener ) {
      ele.removeEventListener( type, handler, false );
    } else if ( ele.detachEvent ) {
      ele.detachEvent( 'on' + type, handler );
    } else {
      ele[ 'on' + type ] = null;
    }
  }
}
Copy after login

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

Basic JavaScript tips (picture and text tutorials, detailed answers for you)

Traversing the values ​​​​in the EL expression List collection in javascript

Detailed analysis and answers to the principle of JavaScript operation

The above is the detailed content of Detailed explanation of event flow and event handlers in JavaScript (graphic tutorial). For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Recommended: Excellent JS open source face detection and recognition project Recommended: Excellent JS open source face detection and recognition project Apr 03, 2024 am 11:55 AM

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages ​​and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts Dec 18, 2023 pm 03:39 PM

With the rapid development of Internet finance, stock investment has become the choice of more and more people. In stock trading, candle charts are a commonly used technical analysis method. It can show the changing trend of stock prices and help investors make more accurate decisions. This article will introduce the development skills of PHP and JS, lead readers to understand how to draw stock candle charts, and provide specific code examples. 1. Understanding Stock Candle Charts Before introducing how to draw stock candle charts, we first need to understand what a candle chart is. Candlestick charts were developed by the Japanese

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

The relationship between js and vue The relationship between js and vue Mar 11, 2024 pm 05:21 PM

The relationship between js and vue: 1. JS as the cornerstone of Web development; 2. The rise of Vue.js as a front-end framework; 3. The complementary relationship between JS and Vue; 4. The practical application of JS and Vue.

How to implement change event binding of select elements in jQuery How to implement change event binding of select elements in jQuery Feb 23, 2024 pm 01:12 PM

jQuery is a popular JavaScript library that can be used to simplify DOM manipulation, event handling, animation effects, etc. In web development, we often encounter situations where we need to change event binding on select elements. This article will introduce how to use jQuery to bind select element change events, and provide specific code examples. First, we need to create a dropdown menu with options using labels:

How to get HTTP status code in JavaScript the easy way How to get HTTP status code in JavaScript the easy way Jan 05, 2024 pm 01:37 PM

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

How to build event-based applications using PHP How to build event-based applications using PHP May 04, 2024 pm 02:24 PM

Methods for building event-based applications in PHP include using the EventSourceAPI to create an event source and using the EventSource object to listen for events on the client side. Send events using Server Sent Events (SSE) and listen for events on the client side using an XMLHttpRequest object. A practical example is to use EventSource to update inventory counts in real time in an e-commerce website. This is achieved on the server side by randomly changing the inventory and sending updates, and the client listens for inventory updates through EventSource and displays them in real time.

js method to refresh current page js method to refresh current page Jan 24, 2024 pm 03:58 PM

js methods to refresh the current page: 1. location.reload(); 2. location.href; 3. location.assign(); 4. window.location. Detailed introduction: 1. location.reload(), use the location.reload() method to reload the current page; 2. location.href, you can refresh the current page by setting the location.href attribute, etc.

See all articles