search
HomeWeb Front-endJS TutorialEvent Types in JavaScript: Common Keyboard and Mouse Events

Event Types in JavaScript: Common Keyboard and Mouse Events

JavaScript provides a wide range of events that allow you to interact with and respond to user actions on a web page. Among these events, keyboard and mouse events are the most commonly used. In this article, we'll look at the different types of keyboard and mouse events in JavaScript and see examples of how to use them.

Keyboard events

Keyboard events occur when the user interacts with the keyboard, such as pressing a key, releasing a key, or typing a character. Keyboard events allow us to do some cool things, such as checking if the user entered something correctly into a form, or that something happens when a specific key is pressed. It's as if the website is listening to the keys you press and reacts accordingly. Keyboard events are divided into three types:

<strong>keydown</strong> Event

This keyboard event is triggered when the user presses a key. If the user holds down a key, it will fire repeatedly.

document.addEventListener('keydown', function(event) {
  console.log('Key pressed is:', event.key);
});

This code demonstrates how the keydown event works. It adds an event listener to the document object's keydown event. When a key on the keyboard is pressed, the specified function is performed. This function logs messages to the console. The message contains the string Key Pressed is:, followed by the value of event.key, which represents the key that was pressed.

keyup Event

This keyboard event occurs when the key is released. It can be used to detect when the user releases a specific key.

document.addEventListener('keyup', (event) => {
    var name = event.key;
    alert(`Key pressed: ${name}`);
}, false);

The above code adds an event listener for the keyup event, so that when a key is released on the keyboard, an arrow function will be executed. The arrow function assigns the value of event.key to a variable named name, which represents the released key. When the key is released, an alert box appears with a message containing the string Key Pressed:, followed by the value of the name variable using string interpolation (${ name}).

Another example that can be used to demonstrate the keyup event is to set up an input field and create a function that converts the characters typed in the input field to uppercase when the user releases the key. To try the example below, create an input tag with the id fname and an input tag like onkeyup="myFunction()" Within the input tag.

function myFunction() {
  let x = document.getElementById("fname"); 
  x.value = x.value.toUpperCase();
}

<strong>keypress</strong> Event

The keypress event is triggered when a key is pressed. In the following code example, an event listener is added to the document object that executes a function when a key is pressed and generates a character value. The arrow function logs a message to the browser's console containing the string Key Pressed:, followed by the value of event.key, which represents the character value of the pressed key . p>

document.addEventListener('keypress', (event) => {
    console.log('Key pressed:', event.key);
});
warn Some browsers no longer support the key event, and not all keys (such as Alt, Control, Shift, or Esc) trigger the event in all browsers. It is recommended to use keydown or keyup events instead.

Example of using keyboard events

Mouse events

On the other hand, mouse events can help you create a more attractive website. They handle events that occur when the mouse interacts with an HTML document, such as clicking, moving, or scrolling. They allow us to react when the user clicks a mouse button, moves the mouse over an element, or drags an item on the screen. It's as if the website is tracking your mouse movements and clicks to figure out what you want to do. There are many types of mouse events:

<strong>Click</strong> Event

This event is executed when the user clicks an element.

var element = document.querySelector('.btn');
element.addEventListener('click', function () {
  element.style.backgroundColor = 'blue';
});

To execute the above code, create a button in HTML with the CSS class name btn. The above code uses the querySelector method to select the element with CSS class name btn and assigns it to the element variable. An event listener listening for the click event has been added to the element. When this element is clicked, the specified function will be performed. The function in this example is to change the background color of the element to blue.

您还可以构建一个简单的游戏,用户可以通过使用 math.floormath.random 方法生成随机颜色,在框内单击以连续更改框的背景颜色。

<strong>dbclick</strong> 事件

当用户用鼠标双击某个元素时,此事件调用一个函数。要执行下面的代码示例,请在 HTML 中创建一个 CSS 类名称为 btn 的按钮。使用 querySelector 方法获取元素并向其添加事件侦听器。双击该按钮时,将调用该函数,显示一条警报消息,并且按钮中文本的字体大小会增加。

var button = document.querySelector('.btn');
button.addEventListener('dblclick', function (event) {
  alert('Button double-clicked!');
  button.style.fontSize = '40px';
});

使用 dbclick 事件的高级方法是使用户能够编辑内容。例如,双击文本元素可以将其转换为可编辑的输入字段,允许用户直接进行更改。下面是使用 dbclick 事件编辑内容的演示。

<strong>mouseup</strong><strong>mousedown</strong> 事件

当用户将光标悬停在某个元素上并按下鼠标按钮时,会触发此 mousedown 事件。 创建一个 id 为 text 的按钮。当用鼠标单击该按钮时,会触发消息:“鼠标按钮已按下”。

var button = document.getElementById('text');
button.addEventListener('mousedown', function (event) {
  alert('Mouse button pressed!');
});

用户单击某个元素后释放鼠标按钮时,会触发 mouseup 事件。创建一个 id 为 text 的按钮。当用鼠标单击按钮并释放时,会触发消息:“鼠标按钮已释放”。

var button = document.getElementById('text');
button.addEventListener('mouseup', function (event) {
  alert('Mouse button released!');
});

如何使用这些 mouseupmousedown 事件的实际示例是在实现拖放功能以及绘图和草图时。

<strong>mouseover</strong><strong>mouseout</strong> 事件

当鼠标指针悬停在某个元素上时,会发生 mouseover 事件,而当鼠标指针离开该元素时,会发生 mouseout 事件。这是这两个鼠标事件的快速演示。

在上面的演示中,当用户的鼠标经过图像时,图像会放大,当鼠标离开图像时,图像会恢复到正常大小。

mouseover 事件可用于创建一个工具提示,当鼠标悬停在元素上时,该提示提供有关该元素的附加信息。 mouseovermouseout 事件还可用于创建交互式导航菜单,其中当用户的鼠标指针悬停在菜单项上时会出现子菜单。

<strong>mousemove</strong><strong>mouseleave</strong> 事件

当用户将鼠标光标移动到某个元素上时,会触发 mousemove 事件,当鼠标光标离开该元素时,会触发 mouseleave 事件。这些事件使开发人员能够监视鼠标移动。

每当用户的鼠标位于 div 容器内时,上述代码都会获取鼠标指针坐标,并将坐标显示为框下方的文本。然后,在用户鼠标离开 div 元素后,它会显示文本,指示指针已离开 div。

结论

诸如 keydownkeyupkeypress 之类的键盘事件允许我们捕获并响应来自键盘的用户输入。无论您是实现表单验证、提供键盘快捷键还是创建基于文本的游戏,键盘事件对于用户交互都是至关重要的。另一方面,鼠标事件,如clickdblclickmousedownmouseupmouseovermouseoutmousemovephpcn endcphpcn 和 <code>mouseleave,允许我们捕获并响应用户与鼠标的交互。

In summary, JavaScript's keyboard and mouse events allow us to build websites that appear to be listening and responding to user activity by capturing key presses and mouse movements. Now that you understand the various types of keyboard and mouse events and how to use them to build interactive websites and web applications, go ahead and build fun interactive games and websites. Happy coding!

The above is the detailed content of Event Types in JavaScript: Common Keyboard and Mouse Events. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
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

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

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)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks 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

Atom editor mac version download

Atom editor mac version download

The most popular open source 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.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor