JavaScript Introduction to Browser Events
JavaScript Introduction to Browser Events (浏览器事件JavaScript简介)
Events are considered occurrences or actions, happening in the system you are developing that the latter informs you about so that you can respond to them. In brief, it is a signal that something has happened in your system. All of the DOM nodes generate signals like that ( of course, they are not limited to DOM). (事件被认为是在您正在开发的系统中发生的事件或行动,后者会通知您,以便您可以对其做出响应。简而言之,这是一个信号,表明您的系统中发生了某些事情。所有DOM节点都会产生类似的信号(当然,它们不限于DOM )。)
To be more precise, let’s consider a situation. For example, if a user clicks a webpage button, you can respond to it by displaying an information box. (更准确地说,让我们考虑一种情况。例如,如果用户单击网页按钮,您可以通过显示信息框来响应。)
Let’s take a look at the handiest DOM events:
Mouse Events:
Mouse Events:
click– when a click is made on an element by the mouse ( touchscreen devices are capable of generating it on tap). (-点击-当鼠标点击元素时(触摸屏设备能够轻触生成)。)
contextmenu – the right-click of the mouse on an element. (-上下文菜单–鼠标右键单击某个元素。)
mouseover/mouseout –when the cursor of the mouse moves onto or leaves an element. (- mouseover/mouseout -当鼠标光标移动到或离开某个元素时。)
mousedown/mouseup - while the mouse button is pressed or is over an element. (- mousedown/mouseup -按下鼠标按钮或位于元素上方。)
mousemove- the mouse is moved. (-鼠标移动-鼠标被移动。)
Form Element Events:
submit - the event of submitting a <form> by the visitor.
focus - focusing on an element by the visitor. (- FOCUS -由访客专注于某个元素。)
Keyboard Events:
Keyboard Events:
keydown - when the visitor presses the button. (-键入-当访客按下按钮时。)
keyup - when any key is released by the visitor. (-钥匙-当访客放开任何钥匙时。)
Document Events:
Document Events:
DOMContentLoaded - the state of loading and proceeding of HTML, the DOM is completely built. (DOMContentLoaded -加载和处理HTML的状态, DOM已完全构建。)
CSS Events
CSS Events (CSS事件)
transitionend - completion of a CSS-animation. (transitionend - CSS动画的完成。)
There are more events, but the ones above are the most essential. (还有更多活动,但上面的活动是最重要的。)
Event Handlers
Event Handlers (事件处理程序)
A handler is assigned for reacting to events: it is a function, running in case of an event. Handlers are a means of running JavaScript code in case of user actions. Several ways of assigning a handler can be distinguished. Let’s explore them, starting from the most straightforward one.
HTML-attribute
You can set a handler in HTML with an attribute called on<event>. For example, if you want to assign a click handler for an input, use onclick, as follows:
<input value="Click" onclick="alert('Click')" type="button">
The code inside onclick runs on mouse click. Please, take into account that you need to use single quotes inside onclick. The reason is that the attribute itself is inside double-quotes. Forgetting that the code is inside the attribute and using double quotes inside (onclick=“alert(‘Click’)”) will lead to an error. An HTML-attribute is not the proper place for writing too much code. Hence, it would be best if you created a JavaScript function and called it. (Onclick中的代码在鼠标单击时运行。请注意,您需要在onclick中使用单引号。原因是属性本身位于双引号内。忘记代码在属性内,并在其中使用双引号( onclick = “alert (‘Click’)” )将导致错误。HTML属性不是编写太多代码的适当位置。因此,最好创建一个JavaScript函数并调用它。)
The click in the following example will run the carsCount() function:
<!DOCTYPE html>
<html>
<head>
<title>Title of the Document</title>
</head>
<body>
<script>
function carsCount() {
for(let i = 1; i <= 5; i++) {
alert("Car " + i);
}
}
</script>
<input type="button" onclick="carsCount()" value="Cars count">
</body>
</html>
let input = document.createElement('input');
input.id = 'inputId';
input.setAttribute("type", "button");
input.setAttribute("value", "Click");
document.body.appendChild(input);
inputId.onclick = function carsCount() {
for (let i = 1; i <= 5; i++) {
alert("Car " + i);
}
}
As you know, the HTML attribute names are not considered case-sensitive: ONCLICK will work as onClick and onCLICK. But, as a rule, attributes should be lowercase: for example, onclick.
DOM Property
A handler can also be assigned with a DOM property on<event>. Let’s see elem.onclick in the example below:
<!DOCTYPE html>
<html>
<head>
<title>Title of the Document</title>
</head>
<body>
<input id="inputId" type="button" value="Click">
<script>
inputId.onclick = function() {
alert('Welcome to w3cdoc');
};
</script>
</body>
</html>
And the same thing in javascript:
let input = document.createElement('input');
input.id = 'inputId';
input.setAttribute("type", "button");
input.setAttribute("value", "Click");
document.body.appendChild(input);
inputId.onclick = function () {
console.log('Welcome to w3cdoc');
};
In case the handler is assigned by using an HTML-attribute, the browser will be able to read it, creating a new function from the attribute content and writing it to the DOM property. (如果通过使用HTML属性分配处理程序,浏览器将能够读取它,从属性内容创建一个新函数并将其写入DOM属性。)
Please, note that the handler is always in the DOM property, and the HTML-attribute is one of the ways of initializing it. (请注意,处理程序始终位于DOM属性中,而HTML属性是初始化它的方法之一。)
Let’s view two codes that operate the same:
<!DOCTYPE html>
<html>
<head>
<title>Title of the Document</title>
</head>
<body>
<input type="button" onclick="alert('Click')" value="Button">
</body>
</html>
You can’t assign more than a single event handler, because there is only one onclick property. Let’s take an example where handling with JavaScript overwrites the handler that already exists. (不能分配多个事件处理程序,因为只有一个onclick属性。让我们以一个示例为例,其中使用JavaScript处理会覆盖已存在的处理程序。)
<!DOCTYPE html>
<html>
<head>
<title>Title of the Document</title>
</head>
<body>
<input type="button" id="buttonId" value="Button">
<script>
buttonId.onclick = function() {
alert('Click');
};
</script>
</body>
</html>
By the way, direct assigning an existing function as a handler is possible, like here:
let div = document.createElement('div');
div.id = 'elem';
div.innerHTML = 'Click on text';
document.body.appendChild(div);
function welcome() {
alert('Welcome to w3cdoc');
}
elem.onclick = welcome;
For removing a handler, you should assign elem.onclick = null. (要删除处理程序,应分配elem.onclick = null。)
Accessing the Element: this
Accessing the Element: this
The element is the value of this inside a handler. Let’s see an example where button through this.innerHTML shows its content:
<!DOCTYPE html>
<html>
<head>
<title>Title of the Document</title>
</head>
<body>
<button onclick="alert(this.innerHTML)">Click me</button>
</body>
</html>
And the same thing in javascript:
let button = document.createElement('button');
button.innerHTML = 'Click on button';
document.body.appendChild(button);
button.onclick = function () {
console.log(this.innerHTML);
};
Possible Mistakes
Possible Mistakes (可能的错误)
There can be subtleties in the process of working with events. The function needs to be assigned as welcome, not welcome() like in the example below:
// right
button.onclick = welcome;
// wrong
button.onclick = welcome();
In the event of adding parentheses,welcome() is a function call. So, the last line will take the result of the function execution. It is undefined, as the function doesn’t return anything, so it is assigned to onclick. That will not work. On the other hand, the parentheses are necessary for the markup, as follows:
<!DOCTYPE html>
<html>
<head>
<title>Title of the Document</title>
</head>
<body>
<input type="button" id="button" onclick="welcome()" value="Button">
<script>
function welcome() {
alert('Welcome')
(alert ('欢迎'))
}
</script>
</body>
</html>
Let’s explain the difference. At the time the browser reads the attribute, it generates a handler function using the body from the content of it: welcome(). Therefore the markup creates the property below:
<!DOCTYPE html>
<html>
<head>
<title>Title of the Document</title>
</head>
<body>
<input type="button" id="button" value="Button">
<script>
function welcome() {
alert('Welcome')
(alert ('欢迎'))
}
button.onclick = function() {
welcome(); // the attribute content
}
</script>
</body>
</html>
It is recommended to use functions and not strings. (建议使用函数而不是字符串。)
The elem.onclick = “alert(1)” also works but we don’t recommend you to use it. (Elem.onclick = “alert (1)“也可用,但我们不建议您使用它。)
You shouldn’t use setAttribute either. (您也不应该使用setAttribute。)
It is useless to call the following:
// a click on <body> will generate errors,
// because attributes are always strings, function becomes a string
document.body.setAttribute('onclick', function () {
alert(1)
});
Keep in mind the DOM-property case: assign a handler to elem.onclick and not to elem.ONCLICK. The reason is already spoken about: the properties of DOM are case-sensitive.
addEventListener
There is a fundamental problem in the ways of assigning handlers above- they don’t allow you to add multiple handlers to a single event. For example, if it is necessary to highlight a button on click in one part of your code and to show code in another one. If you assign two event handlers for that, the DOM property will overwrite the existing one, like this:
let input = document.createElement('input');
input.setAttribute('type', 'button');
input.setAttribute('value', 'Button');
document.body.appendChild(input);
input.onclick = function () {
alert(1);
}
// ...
input.onclick = function () {
alert(2);
} // replaces the previous handler
Using the specific methods, such as addEventListener addEventListener and removeEventListenerremoveEventListener will free you from that kind of problem. The syntax to add a handler will look like this:
element.addEventListener(event, handler[, options]);
event (事件)
Event name ( for example, click). (事件名称(例如,单击)。)
handler (恅璃靡ㄗfilenameㄘ)
The function of the handler. (处理程序的功能。)
options
An additional optional object obtaining the following properties:
once: in case it’s true, the listener will automatically be removed after it releases.
capture: the phase where the event should be handled. More about it is represented in chapter Bubbling and capturing.
passive: in the case of true, the handler will not be preventDefault().
Finally, for removing the handler, you can apply removeEventListener, like this:
element.removeEventListener(event, handler[, options]);
Event Object
Event Object (事件对象)
For handling the event properly, you need to get more detailed information about what has happened. It’s not just about a keypress or a click, but about the exact pointer coordinates. (为了正确处理事件,您需要获得有关事件的更多详细信息。这不仅仅是按键或点击,而是关于确切的指针坐标。)
Whenever an event happens, an event object is created by your browser: all the details are inserted to it, and it is passed as a handler argument. Let’s take a look at an example, where the mouse coordinates are got from the event object:
<!DOCTYPE html>
<html>
<head>
<title>Title of the Document</title>
</head>
<body>
<input type="button" value="Click" id="inputId">
<script>
inputId.onclick = function(event) {
// show event type, element and coordinates of the click
(//显示点击的事件类型、元素和坐标)
alert(event.type + " at " + event.currentTarget);
alert("Coordinates: " + event.clientX + ":" + event.clientY);
};
</script>
</body>
</html>
And the same thing in javascript:
let input = document.createElement('input');
input.id = 'inputId';
input.setAttribute('type', 'button');
input.setAttribute('value', 'Click');
document.body.appendChild(input);
inputId.onclick = function (event) {
// show event type, element and coordinates of the click
(//显示点击的事件类型、元素和坐标)
alert(event.type + " at " + event.currentTarget);
alert("Coordinates: " + event.clientX + ":" + event.clientY);
};
Some of the properties of the event object are the following:
event.type: the type of the event ( in the example above, it’s “click”).
event.currentTarget: the element, which handled the event. It is equivalent to this, unless the handler belongs to arrow functions, or this is linked to something else. Then you should get the element from event.currentTarget.
event.clientX / event.clientY: these are the cursor’s window-relative coordinates, for the mouse.
The properties of the event object are not limited to what was represented above, but these are the most common ones. (事件对象的属性不限于上面表示的内容,但这些是最常见的属性。)
Object handlers: handleEvent
Object handlers: handleEvent
Like a function, an object can also be assigned as an event handler with the help of addEventListener. Whenever an event happens, its handleEvent method is called, like here:
<!DOCTYPE html>
<html>
<head>
<title>Title of the Document</title>
</head>
<body>
<button id="buttonId">Click</button>
<script>
buttonId.addEventListener('click', {
handleEvent(event) {
alert(event.type + " at " + event.currentTarget);
}
});
</script>
</body>
</html>
You can notice that addEventListener gets an object as a handler, calling object.handleEvent(event) in case of an event. (您可以注意到, addEventListener获取对象作为处理程序,在发生事件时调用object.handleEvent (event)。)
A class can also be used for that purpose, like this:
<!DOCTYPE html>
<html>
<head>
<title>Title of the Document</title>
</head>
<body>
<button id="buttonId">Click me</button>
<script>
class Welcome {
handleEvent(event) {
switch(event.type) {
case 'mousedown':
buttonId.innerHTML = "Welcome to";
break;
case 'mouseup':
buttonId.innerHTML += "... w3cdoc.";
break;
}
}
}
let welcome = new Welcome();
buttonId.addEventListener('mousedown', welcome);
buttonId.addEventListener('mouseup', welcome);
</script>
</body>
</html>
However, the handleEvent method doesn’t have to do the whole job alone. It might call other event-specific methods too. Here is an example of calling an event-specific method:
<!DOCTYPE html>
<html>
<head>
<title>Title of the Document</title>
</head>
<body>
<button id="buttonId">Click me</button>
<script>
class Welcome {
handleEvent(event) {
// mousedown -> onMousedown
(//mousedown - > onMousedown)
let method = 'on' + event.type[0].toUpperCase() + event.type.slice(1);
this[method](event);
}
// Mouse button pressed
(//按下鼠标按钮)
onMousedown() {
buttonId.innerHTML = "Welcome to ";
}
//and released
(//并被释放)
onMouseup() {
buttonId.innerHTML += "...w3cdoc.";
}
}
let welcome = new Welcome();
buttonId.addEventListener('mousedown', welcome);
buttonId.addEventListener('mouseup', welcome);
</script>
</body>
</html>
Summary
Summary (概要)
Events are not a part of the core JavaScript: they are defined in the browser Web APIs.
For any website with dynamic functionality, it is vital to deal with users that interact with them. In practice, events are the means that make it possible. (对于任何具有动态功能的网站,与与其交互的用户打交道至关重要。在实践中,事件是使之成为可能的手段。)
In general, events are a signal that something has occurred, telling you to respond to it. (一般来说,事件是某事发生的信号,告诉你要对它做出反应。)
There exist 3 ways of assigning the event handlers:
HTML attribute, such as onclick=”…”. (- HTML属性,例如onclick = “…"。)
The property of DOM: elem.onclick = function.
Methods of adding and removing. Among them are elem.addEventListener(event, handler[, phase]) (for adding) and removeEventListener (for removing). (-添加和删除的方法。其中包括elem.addEventListener (event, handler [, phase]) (用于添加)和removeEventListener (用于删除)。)
You need to use HTML properties moderately, as JavaScript can look a little odd in the middle of an HTML tag. Also, it is not possible to write a lot of code in it. (您需要适度使用HTML属性,因为JavaScript在HTML标记中间可能看起来有点奇怪。此外,不可能在其中编写大量代码。)
You can also use the DOM properties, but it is not possible to assign more than a handler of the specific event. (您还可以使用DOM属性,但不能为特定事件分配多个处理程序。)
The last point, noted above, is the most flexible one. But, it’s the longest way of writing. (上面提到的最后一点是最灵活的。但是,这是最长的写作方式。)