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 |