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('p'); 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:
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.
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('p'); p.textContent = "I changed because of an event handler property."; } // Add event handler as a property of the button element const button = document.querySelector('button'); 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:
Now, when you click this button, it will have a Similar effect:
#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('p'); const button = document.querySelector('button'); const changeText = () = >{ p.textContent = "Will I change?"; } const alertText = () = >{ alert('Will I alert?'); } // Events can be overwritten button.onclick = changeText; button.onclick = alertText;
在上面的例子中,单击按钮只会显示一个警告,而不会更改p文本,因为alert()代码是最后添加到属性的代码。
了解了内联事件处理程序和事件处理程序属性之后,让我们转向事件侦听器。
事件监听器
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('p'); p.textContent = "I changed because of an event listener."; } // Listen for click event const button = document.querySelector('button'); button.addEventListener('click', changeText);
注意,对于前两个方法,click事件被称为onclick,但是对于事件监听器,它被称为click。每个事件监听器都会从单词中删除这个词。在下一节中,我们将查看更多其他类型事件的示例。
当您用上面的JavaScript代码重新加载页面时,您将收到以下输出:
初看起来,事件监听器看起来与事件处理程序属性非常相似,但它们有一些优点。我们可以在同一个元素上设置多个事件侦听器,如下例所示。
const p = document.querySelector('p'); const button = document.querySelector('button'); const changeText = () = >{ p.textContent = "Will I change?"; } const alertText = () = >{ alert('Will I alert?'); } // Multiple listeners can be added to the same event and element button.addEventListener('click', changeText); button.addEventListener('click', alertText);
在本例中,这两个事件都将触发,一旦单击退出警告,就向用户提供一个警告和修改后的文本。
通常,将使用匿名函数而不是事件侦听器上的函数引用。匿名函数是没有命名的函数。
// An anonymous function on an event listener button.addEventListener('click', () = >{ p.textContent = "Will I change?"; });
还可以使用removeEventListener()函数从元素中删除一个或所有事件。
// Remove alert function from button element button.removeEventListener('click', 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.
Event |
Description |
---|---|
Fired when the form is submitted | |
Fired when an element (such as an input) receives focus | |
When an element Triggered when focus is lost |
Keyboard events
Keyboard events are used to handle keyboard operations such as pressing a key, raising a key, and holding a key.Description | |
---|---|
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:
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!

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 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 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.

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.

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.

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.

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

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


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

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
Easy-to-use and free code editor

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
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
The latest (2018.2.1) professional PHP integrated development tool