JS addEventListener() and attachEvent() methods implement registration events

JS addEventListener() and attachEvent() methods implement registration events

In JavaScript's DOM event model, events are registered by calling the addEventListener() method of an object. Usage is as follows:
element.addEventListener(String type, Function listener, boolean useCaptrue);

The parameters are described as follows:

  • type: The type name of the registered event. Event types are different from event attributes. Event type names do not have the "on" prefix. For example, for the event attribute onclick, the corresponding event type is click.
  • listener: listening function, that is, event processing function. This function will be called when an event of the specified type occurs. When this function is called, the only argument passed to it by default is the event object.
  • useCaptrue: is a Boolean value. If true, the specified event handler will be triggered during the capture phase of event propagation; if false, the event handler will be triggered during the bubbling phase.

Example 1

The following example uses addEventListener() to register click events for all buttons. First, call the getElementsByTagName() method of document to capture all button objects; then, use the for statement to traverse the button set (btn), and use the addEventListener() method to register an event function for each button to obtain the text displayed by the current object.

<button id="btn1" onclick="btn1();">Button 1</button>
<button id="btn2" onclick="btn2(event);">Button 2</button>
<script>
  var btn = document.getElementsByTagName("button"); //Capture all buttons for(var i in btn){ //Traverse the button collection btn[i].addEventListener("click", function(){
    alert(this.innerHTML);
  }, true); //Register an event handling function for each button object and define the response in the capture phase}
</script> 

Preview in the browser and click different buttons, the browser will automatically display the button name. The effect is shown in the figure:

Use the addEventListener() method to register the same event handling function for multiple objects, or to register multiple event handling functions for the same object. Registering multiple event handlers for the same object is very useful for modular development.

Example 2

In the following example, two events are registered for paragraph text: mouseover and mouseout. When the cursor moves over paragraph text, it will be displayed with a blue background, and when the cursor moves out of the paragraph text, it will automatically be displayed with a red background. This way, there is no need to destroy the document structure and add multiple event attributes to the paragraph text.

<p id="p1">Register multiple events for an object</p>
<script>
  var p1 = document.getElementById("p1"); //Capture the handle of the paragraph element p1.addEventListener("mouseover", function () {
    this.style.background = 'blue';
  }, true); //Register the first event handler for the paragraph element p1.addEventListener("mouseout", function () {
    this.style.background = 'blue';
  }, true); //Register the second event handler for the paragraph element</script>

The IE event model uses the attachEvent() method to register events. Usage is as follows:

element.attachEvent(etype, eventName)

The parameter list is as follows:

  • etype: Set the event type, such as onclick, onkeyup, onmousemove, etc.
  • eventName: Set the event name, which is the event processing function.

Example 3

In the following example, two events are registered for the paragraph tag <p>: mouseover and mouseout. When the cursor passes by, the background color of the paragraph text is blue, and when the cursor moves away, the background color is red.

<p id="p1">Register multiple events for an object</p>
<script>
  var p1 = document.getElementById("p1"); //Capture paragraph element p1.attachEvent("onmouseover", function () {
    this.style.background = 'blue';
  }); //Register mouseover event p1.attachEvent("onmouseout", function () {
    this.style.background = 'red';
  }); //Register mouseout event</script>

When attachEvent() is used to register an event, the calling object of the event processing function is no longer the current event object itself, but the window object. Therefore, this in the event function points to the window, not the current object. If you want to get the current object, you should use the srcElement attribute of event.

The first parameter of the attachEvent() method in the IE event model is the event type name, which needs to be prefixed with on. When using the addEventListener() method, the on prefix is ​​not required, such as click.

This is the end of this article about JS addEventListener() and attachEvent() methods to implement registration events. For more related JS addEventListener() and attachEvent() content, please search 123WORDPRESS.COM's previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • EventBus in JavaScript implements communication between objects
  • JS event loop mechanism event loop macro task micro task principle analysis
  • Analysis of the difference between Js on and addEventListener principles and usage
  • Simple model explanation and application analysis of JavaScript event loop event loop
  • Case analysis of addEventListener() and removeEventListener() usage in js
  • Understanding and application examples of Event Loop in node.js
  • Detailed explanation of node.JS event mechanism and how to use events module
  • JavaScript MouseEvent Case Study

<<:  JS removeAttribute() method to delete an attribute of an element

>>:  Introduction and usage examples of ref and $refs in Vue

Recommend

How to generate PDF and download it in Vue front-end

Table of contents 1. Installation and introductio...

Setting the engine MyISAM/InnoDB when creating a data table in MySQL

When I configured mysql, I set the default storag...

When backing up files in Centos7, add the backup date to the backup file

Linux uses files as the basis to manage the devic...

Cross-domain issues in front-end and back-end separation of Vue+SpringBoot

In the front-end and back-end separation developm...

A brief introduction to MySQL storage engine

1. MySql Architecture Before introducing the stor...

JavaScript microtasks and macrotasks explained

Preface: js is a single-threaded language, so it ...

How to enable or disable SSH for a specific user or user group in Linux

Due to your company standards, you may only allow...

How to modify server uuid in Mysql

Source of the problem: If the slave server is the...

MySQL transaction details

Table of contents Introduction Four characteristi...

Try Docker+Nginx to deploy single page application method

From development to deployment, do it yourself Wh...

Example of using CSS filter to write mouse over effect

Use CSS filter to write mouse over effect <div...

Nexus private server construction principle and tutorial analysis

one. Why build a Nexus private server? All develo...

Basic operations of mysql learning notes table

Create Table create table table name create table...

Getting Started Tutorial for Beginners ④: How to bind subdirectories

To understand what this means, we must first know ...

How to maintain a long connection when using nginx reverse proxy

· 【Scene description】 After HTTP1.1, the HTTP pro...