search
HomeWeb Front-endJS TutorialDeep understanding of events in JavaScript

Deep understanding of events in JavaScript

Sep 28, 2020 pm 05:56 PM
javascriptprototypeinherit

Deep understanding of events in JavaScript

In this article, we will discuss event handlers, event listeners, and event objects. We'll also cover three different ways to handle events, as well as some of the most common ones. By understanding events, you will be able to provide users with a more interactive web experience.

Events are operations that occur in the browser and can be initiated by the user or the browser itself. Here are some common events that happen on websites:

  • Page completes loading

  • User clicks a button

  • User hovers over dropdown list

  • User submits form

  • User presses key on keyboard

By encoding JavaScript responses that execute on events, developers can display messages to the user, validate data, react to button clicks, and perform many other actions.

Event Handlers and Event Listeners

When the user clicks a button or presses a key, an event is triggered. These are called click events or key events respectively.

An event handler is a JavaScript function that runs when an event triggers.

An event listener is attached to a responsive interface element, which allows a specific element to wait and "listen" for a given event to fire.

There are three ways to assign events to elements:

  • Inline event handler

  • Event handler properties

  • Event Listener

We'll go over these three methods in detail to make sure you're familiar with each method of triggering an event, and then discuss the specifics of each method Pros and cons.

Inline Event Handler Properties

To start learning about event handlers, we first consider inline event handlers. Let's start with a very basic example consisting of a button element and a p element. We want the user to click a button to change the text content of p.

Let’s start with an HTML page with a button. We will reference a JavaScript file to which we will add code later.

<!DOCTYPE html>
<html>
  
  <head>
    <title>Events</title></head>
  
  <body>
    <!-- Add button -->
    <button>Click me</button>
    <p>Try to change me.</p>
  </body>
  <!-- Reference JavaScript file -->
  <script src="js/events.js"></script>

</html>

Directly on the button, we will add an attribute called onclick. The property value will be a function we created called changeText().

<!DOCTYPE html>
<html>
  
  <head>
    <title>Events</title></head>
  
  <body>
    <button onclick="changeText()">Click me</button>
    <p>Try to change me.</p>
  </body>
  <script src="js/events.js"></script>

</html>

Let's create the events.js file, which is located in the js/ directory here. In it, we will create the changeText() function, which will modify the textContent of the p element.

// Function to modify the text content of the paragraph
const changeText = () = >{
    const p = document.querySelector(&#39;p&#39;);

    p.textContent = "I changed because of an inline event handler.";
}

The first time you load events.html, you'll see a page that looks like this:

Deep understanding of events in JavaScript

However, when you or another user clicks the button, The text of the p tag will change from Try to change me to . I changed it because of inline event handlers.

Deep understanding of events in JavaScript

Inline event handlers are a straightforward way to start understanding events, but they should generally not be used beyond testing and educational purposes.

You can compare inline event handlers to inline CSS styles on HTML elements. Maintaining a separate class stylesheet is more practical than creating inline styles on each element, just like maintaining JavaScript that is handled entirely through a separate script file rather than adding handlers to each element.

Event Handler Properties

The next step in inlining event handlers is the event handler properties. This is very similar to an inline handler, except we set the attribute of the element in JavaScript rather than in HTML.

The settings here are the same, except we no longer include onclick="changeText()":

… < body >

<button > Click me < /button>

    <p>I will change.</p >

</body>
…/

Our function will also Stay similar, only now we need to access the button element in JavaScript. We can simply access onclick just like we would access style or id or any other element attribute and then assign the function reference.

// Function to modify the text content of the paragraph
const changeText = () = >{
    const p = document.querySelector(&#39;p&#39;);

    p.textContent = "I changed because of an event handler property.";
}

// Add event handler as a property of the button element
const button = document.querySelector(&#39;button&#39;);
button.onclick = changeText;

Note: Event handlers do not follow the camelCase convention that most JavaScript code follows. Note that the code is onclick, not onclick.

When you first load a web page, your browser will display the following:

Deep understanding of events in JavaScript

Now, when you click this button, it will have a Similar effect:

Deep understanding of events in JavaScript

#Note that when passing the function reference to the onclick attribute, we do not include the parentheses because we are not calling the function at that time, but just passing it citation.

事件处理程序属性的可维护性略好于内联处理程序,但它仍然存在一些相同的障碍。例如,尝试设置多个单独的onclick属性将导致覆盖除最后一个外的所有属性,如下所示。

const p = document.querySelector(&#39;p&#39;);
const button = document.querySelector(&#39;button&#39;);

const changeText = () = >{
    p.textContent = "Will I change?";
}

const alertText = () = >{
    alert(&#39;Will I alert?&#39;);
}

// Events can be overwritten
button.onclick = changeText;
button.onclick = alertText;

在上面的例子中,单击按钮只会显示一个警告,而不会更改p文本,因为alert()代码是最后添加到属性的代码。

Deep understanding of events in JavaScript

了解了内联事件处理程序和事件处理程序属性之后,让我们转向事件侦听器。

事件监听器

JavaScript事件处理程序的最新添加是事件侦听器。事件侦听器监视元素上的事件。我们将使用addEventListener()方法侦听事件,而不是直接将事件分配给元素上的属性。

addEventListener()接受两个强制参数——要侦听的事件和侦听器回调函数。

事件监听器的HTML与前面的示例相同。

… < button > Click me < /button>

    <p>I will change.</p > …

我们仍然将使用与以前相同的changeText()函数。我们将把addEventListener()方法附加到按钮上。

// Function to modify the text content of the paragraph
const changeText = () = >{
    const p = document.querySelector(&#39;p&#39;);

    p.textContent = "I changed because of an event listener.";
}

// Listen for click event
const button = document.querySelector(&#39;button&#39;);
button.addEventListener(&#39;click&#39;, changeText);

注意,对于前两个方法,click事件被称为onclick,但是对于事件监听器,它被称为click。每个事件监听器都会从单词中删除这个词。在下一节中,我们将查看更多其他类型事件的示例。

当您用上面的JavaScript代码重新加载页面时,您将收到以下输出:

Deep understanding of events in JavaScript

初看起来,事件监听器看起来与事件处理程序属性非常相似,但它们有一些优点。我们可以在同一个元素上设置多个事件侦听器,如下例所示。

const p = document.querySelector(&#39;p&#39;);
const button = document.querySelector(&#39;button&#39;);

const changeText = () = >{
    p.textContent = "Will I change?";
}

const alertText = () = >{
    alert(&#39;Will I alert?&#39;);
}

// Multiple listeners can be added to the same event and element
button.addEventListener(&#39;click&#39;, changeText);
button.addEventListener(&#39;click&#39;, alertText);

在本例中,这两个事件都将触发,一旦单击退出警告,就向用户提供一个警告和修改后的文本。

通常,将使用匿名函数而不是事件侦听器上的函数引用。匿名函数是没有命名的函数。

// An anonymous function on an event listener
button.addEventListener(&#39;click&#39;, () = >{
    p.textContent = "Will I change?";
});

还可以使用removeEventListener()函数从元素中删除一个或所有事件。

// Remove alert function from button element
button.removeEventListener(&#39;click&#39;, alertText);

此外,您可以在文档和窗口对象上使用addEventListener()。

事件监听器是当前在JavaScript中处理事件的最常见和首选的方法。

常见的事件

我们已经了解了使用click事件的内联事件处理程序、事件处理程序属性和事件侦听器,但是JavaScript中还有更多的事件。下面我们将讨论一些最常见的事件。

鼠标事件

鼠标事件是最常用的事件之一。它们指的是涉及单击鼠标上的按钮或悬停并移动鼠标指针的事件。这些事件还对应于触摸设备上的等效操作。

事件
描述
click 当鼠标被按下并释放到元素上时触发
dblclick 当元素被单击两次时触发
mouseenter 当指针进入元素时触发
mouseleave 当指针离开一个元素时触发
mousemove 每当指针在元素中移动时触发

Click is a compound event, consisting of the combined mousedown and mouseup events, which are triggered when the mouse button is pressed or raised respectively.

Use mouseenter and mouseleave simultaneously to create a hover effect that will last as long as the mouse pointer stays on the element.

Form Events

Form events are form-related actions, such as which input elements are being selected or unselected, and which form is being submitted.

##submitFired when the form is submittedfocusFired when an element (such as an input) receives focus blurWhen an element Triggered when focus is lost
Event
Description
#Focus is achieved when an element is selected, e.g. by mouse click or by navigating to it via the TAB key.

JavaScript is commonly used to submit forms and send values ​​to backend languages. The advantages of using JavaScript to send a form are that submitting the form does not require reloading the page, and the required input fields can be validated using JavaScript.

Keyboard events

Keyboard events are used to handle keyboard operations such as pressing a key, raising a key, and holding a key.

EventDescription##keydownkeyupkeypressAlthough they look similar, the keydown and keypress events do not access all the exact same keys. keydown will acknowledge each key pressed, while keypress will omit keys that do not generate characters, such as SHIFT, ALT, or DELETE.

A key is pressed It will trigger once when
Trigger once when releasing the key
Continuously when pressing the key Fire

Keyboard events have specific properties for accessing individual keys.

If we pass a parameter called an event object to an event listener, we can access more information about the action that occurred. The three properties related to the keyboard object include keyCode, key and code.

For example, if the user presses the letter a key on the keyboard, the following properties related to that key will appear:

PropertieskeyCodekeycode

为了展示如何通过JavaScript控制台收集这些信息,我们可以编写以下代码行。

// Test the keyCode, key, and code properties
document.addEventListener(&#39;keydown&#39;, event = >{
    console.log(&#39;key: &#39; + event.keyCode);
    console.log(&#39;key: &#39; + event.key);
    console.log(&#39;code: &#39; + event.code);
});

一旦在控制台上按下ENTER键,现在就可以按键盘上的键了,在本例中,我们将按a。

输出:

keyCode: 65
key: a
code: KeyA

keyCode属性是一个与已按下的键相关的数字。key属性是字符的名称,它可以更改——例如,用SHIFT键按下a将导致键为a。code属性表示键盘上的物理键。

注意,keyCode正在被废弃,最好在新项目中使用代码。

事件对象

该Event对象由所有事件都可以访问的属性和方法组成。除了通用Event对象之外,每种类型的事件都有自己的扩展名,例如KeyboardEvent和MouseEvent。

该Event对象作为参数传递给侦听器函数。它通常写成event或e。我们可以访问事件的code属性keydown来复制PC游戏的键盘控件。

要试用它,请使用

标记创建基本HTML文件并将其加载到浏览器中。

<!DOCTYPE html>
<html>
  
  <head>
    <title>Events</title></head>
  
  <body>
    <p>
    </p>
  </body>

</html>

然后,在浏览器的开发者控制台中键入以下JavaScript代码。

// Pass an event through to a listener
document.addEventListener(&#39;keydown&#39;, event = >{
    var element = document.querySelector(&#39;p&#39;);

    // Set variables for keydown codes
    var a = &#39;KeyA&#39;;
    var s = &#39;KeyS&#39;;
    var d = &#39;KeyD&#39;;
    var w = &#39;KeyW&#39;;

    // Set a direction for each code
    switch (event.code) {
    case a:
        element.textContent = &#39;Left&#39;;
        break;
    case s:
        element.textContent = &#39;Down&#39;;
        break;
    case d:
        element.textContent = &#39;Right&#39;;
        break;
    case w:
        element.textContent = &#39;Up&#39;;
        break;
    }
});

当您按下一个键- ,a,s,d或者w-你会看到类似以下的输出:

Deep understanding of events in JavaScript

从这里开始,您可以继续开发浏览器的响应方式以及按下这些键的用户,并可以创建更加动态的网站。

接下来,我们将介绍一个最常用的事件属性:target属性。在下面的示例中,我们div在一个内部有三个元素section。

<!DOCTYPE html>
<html>
  
  <head>
    <title>Events</title></head>
  
  <body>
    <section>
      <div id="one">One</div>
      <div id="two">Two</div>
      <div id="three">Three</div></section>
  </body>

</html>

使用事件。在浏览器的开发人员控制台中,我们可以将一个事件侦听器放在外部section元素上,并获得嵌套最深的元素。

const section = document.querySelector(&#39;section&#39;);

// Print the selected target
section.addEventListener(&#39;click&#39;, event = >{
    console.log(event.target);
});

单击其中任何一个元素都将使用event.target将相关特定元素的输出返回到控制台。这非常有用,因为它允许您只放置一个事件侦听器,该侦听器可用于访问许多嵌套元素。

Deep understanding of events in JavaScript

使用Event对象,我们可以设置与所有事件相关的响应,包括通用事件和更具体的扩展。

结论

事件是在网站上发生的操作,例如单击,悬停,提交表单,加载页面或按键盘上的键。当我们能够让网站响应用户所采取的操作时,JavaScript就变得真正具有互动性和动态性。

更多编程相关知识,请访问:编程入门!!

Description Example
The number associated with the key. 65
represents the character name a
Indicates the physical key pressed KeyA

The above is the detailed content of Deep understanding of events in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:digitalocean. If there is any infringement, please contact admin@php.cn delete
Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

See all articles

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 Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool