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

Detailed explanation of the process of installing msf on Linux system

Or write down the installation process yourself! ...

MySQL transaction analysis

Transaction A transaction is a basic unit of busi...

MySQL database advanced query and multi-table query

MySQL multi-table query Add a worksheet -- User t...

Use of Linux cal command

1. Command Introduction The cal (calendar) comman...

How to point the target link of a tag to iframe

Copy code The code is as follows: <iframe id=&...

Solution to 1045 error in mysql database

How to solve the problem of 1045 when the local d...

Open the app on the h5 side in vue (determine whether it is Android or Apple)

1. Development environment vue+vant 2. Computer s...

A simple method to modify the size of Nginx uploaded files

Original link: https://vien.tech/article/138 Pref...

In-depth understanding of MySQL various locks

Table of contents Lock Overview Lock classificati...

Docker uses a single image to map to multiple ports

need: The official website's resource server ...

Complete steps to build a Laravel development environment using Docker

Preface In this article, we will use Docker to bu...

Design and implementation of Vue cascading drop-down box

Table of contents 1. Database design 2. Front-end...