JavaScript event handling


JS realizes interface interaction with event driven. The core of event driven: message based and event driven. Generally speaking, events are specific events that occur in a document or browser window

Interactive behaviors, such as loading, clicking, input, selection, etc.

1.1 event basis

The interaction between JS and html is realized through events. Events are some specific interaction moments in documents or browser windows. Events exist in the form of objects in the browser, that is, event. When an event is triggered, an event object event will be generated. The object contains all the information related to the event, including the element causing the event, the type of the event and other information related to a specific event.

1.1.1 event model

In the history of browser development. The following have emerged:Four event handling models:

  1. Basic event model: also known as dom0 level event model, it is a relatively simple event model in the early stage of browser development, mainly through event attributes; Binds an event handler for the specified label.


Because this model is widely used and supported by all browsers, it is still popular.


However, this model relies heavily on HTML document tags, which is not conducive to the independent development of JS.

2. DOM event model: developed by W3C, it is the current standard event processing model. All standard compliant browsers support this event model. DOM event model includes dom2 event model and dom3 event model,

Dom3 event model is an upgraded version of dom2 event model, which is slightly improved. It mainly adds some event types to meet the development needs of mobile devices, but most of the specifications and usage are consistent.

3. Ie event model: IE4 0 and above browsers support, which is similar to the DOM event model, but the usage is different.

4. Netscape event model: implemented by Netscape 4 browser and stopped supporting in Netscape 6.

1.1.2 event flow

Event flow is the sequence in which multiple node objects respond to the same event. It mainly includes three types.

1.Bubbling type

Events are triggered from the most specific target to the least specific target, that is, events respond from bottom to top. This transmission process is vividly called bubbling.

The following usage:

function bubble() {
var div = document.getElementsByTagName('div');
var show = document.getElementById('show');
for (var i = 0; i < div.length; i++) {

div[i].onclick = (function (i) {

return function () {

div[i].style.border = '1px dashed orange';

show.innerHTML += div[i].className + '>';





window.onload = bubble;
2. Capturetype

The event is triggered from the least specific target, and finally to the most specific target, that is, the event responds from top to bottom.


for (var i = 0; i < div.length; i++) {
div[i]. /*onclick*/ addEventListener('click', (function (i) {
return function () {
div[i].style.border = '1px dashed orange';
show.innerHTML += div[i].className + '>';
})(i), true);
3. Mixingtype

The DOM event model of W3C supports capture type and bubble type event flow, but capture type event flow occurs first, and then bubble type event flow occurs. Two kinds of event flows touch all the events in the dom

There are hierarchical objects, starting with the document object and ending with the document object.

Depending on the type of event flow.

The whole process of event propagation can be divided into three stages as follows:

Capture phase

Events are propagated down the document tree from the document object to the target node.

Target stage

Events registered on the target node are executed.

bubbling phase

Events are triggered upward from the target node.

1.1.3 event type

According to different trigger objects, events in the browser can be divided into different types.

Dom0 level events define the following event types:

① Mouse events: various behaviors related to mouse operation.It can be divided into two categories:

E.g. (mouseover, mouseout)

Tracks the event that the mouse is currently positioned

E.g. (mouseup, MouseDown, click)

Track mouse click events

② Keyboard events: various behaviors related to keyboard operations, including tracking keyboard strokes and their context.

There are three types of tracking keyboard:

  1. keyup

  2. keydown

  3. keypress

③ Page events: about the behavior of the page itself. For example, the load event is triggered when the page is loaded for the first time and when the page is leftunloadandbeforeunloadevent.

④ UI events: track various behaviors of users in the page. For example, to listen to users’ input in a form, you canfocusandblurTwo events.

In the dom2 event model, the event model contains four sub modules, and each sub module provides support for certain types of events.

The ‘default action’ column defines whether the event type is supportedPreventdefault() method, cancel the default action of the event.

Some new events have been added to the DOM 3 event model.

Dom3 event types are briefly described as follows:

UI (user interface) events

Triggered when the user interacts with an element on the page.

focal event

Triggered when an element gains or loses focus.

Mouse event

Triggered when the user performs an operation on the page through the mouse.

Roller event

Triggered when a mouse wheel or similar device is used.

Text event

Triggered when text is entered in a document.

Keyboard events

Triggered when the user performs an operation on the page through the keyboard.

Composite event

Triggered when a character is entered for ime.

Change event

Triggered when the underlying DOM structure changes.

1.1.4 binding events

In the basic event model, JS supports two binding modes.

1. Static binding

Take the JS script as the attribute value and directly assign the event attribute.

The following usage:


2. Dynamic binding

Assign values using the event properties of the DOM object.

The following usage:

var button = document.getElementById('btn');
button.onclick = function () {
document. Write ('I'm a programmer! ');

This method can directly attach events to page elements in the script without destroying the HTML structure, which is more flexible than the previous one.

1.1.5 event handling function

Event handling function is a special kind of function, whose structure is the same as the function direct quantity. Its main task is to realize event handling. The use method is asynchronous call, and the response is triggered by the event.

Event handlers generally do not have an explicit return value. However, in a specific event, the user can use the return value of the event handler function to affect the execution of the program.

The following usage:

function btn1(event) {
event = event || window.event;
var btn11 = event.srcElement ? event.srcElement :; = 'green';
function btn2(event) {
event = event || window.event;
var src = event.srcElement ? event.srcElement :; = 'skyblue';

1.1.6 registration events

In the DOM event model, by calling theAddeventlistener() methodRegister events.


 element.addEventListener(type, listener, useCapture); 


  • type(a string representing the type of listening event.)

  • listener(when the monitored event type is triggered, an event notification (an object that implements the event interface) object will be received.

  • listenerIt must be an implementationEventListener Interface, or a function.)

  • useCapture(Boolean, in the DOM tree, the element of listener is registered. Do you want to call the listener before the EventTarget below it.

  • WhenuseCapture(set to true), the event bubbling up along the DOM tree will not trigger the listener.

  • When an element is nested with another element, and both elements register a handler for the same event, event bubbling and event capture are two different ways of event propagation.

  • The event propagation pattern determines the order in which elements receive events. If not specified, usecapture defaults to false.)

The following usage:

var p1 = document.getElementById('p1');
p1.addEventListener('mouseover', function () { = 'green';
}, true);
p1.addEventListener('mouseout', function () { = 'red';
}, true);

1.1.7 destruction event

In the DOM event model, useRemoveeventlistener() methodYou can delete the registered event handler from the specified object.


element.removeEventListener(event, function, useCapture)


event must. The name of the event to remove.
function must. Specifies the function to remove.
useCapture Optional. Boolean value that specifies the stage at which the event handle is removed.

Possible values:

True – removes the event handle during the capture phase.

False – default. Handle bubbling event is removed during the bubbling phase.

Note:If you add event handles twice, once in the capture phase and once in the bubble phase, you must remove the event separately.

The following usage:

var span1 = document.getElementById('span1');
var f1 = function () { = 'pink';
var f2 = function () { = 'skyblue';
span1.removeEventListener('mouseover', f1);
span1.removeEventListener('mouseout', f2);
span1.addEventListener('mouseover', f1);
span1.addEventListener('mouseout', f2);

1.1.8 event delegation

JS event delegation is to delegate the event that should have been added to an element to its parent by using the bubble principle, so as to reduce DOM interaction and achieve web page optimization.


Optimize code

Improve operation performance

Truly separating HTML from JS can also prevent the loss of registered events in the process of dynamically adding or deleting nodes.

The following usage:

var ul = document.getElementById('list');
ul.addEventListener('click', function (e) {
var e = e || window.event;
var target = || e.srcElement;
if ( && == 'LI') {
}, true);
var i = 4;
var btn = document.getElementById('btn');
btn.addEventListener('click', function () {
var li = document.createElement('li');
li. InnerHTML = 'I'm a programmer' + I + +;

1.2 mouse events

Mouse event is the most commonly used event type in web development.

1.2.1 mouse click

Mouse click events include 4:


single click







Among themclickEvent types are most commonly used, whilemousedownandmouseupEvent types are mostly used in mouse drag and drop and stretch operations. When the return value of these event handling functions is false,

The default behavior of the bound object is disabled.

The following usage:

var a = document.getElementsByTagName('a');
for (var i = 0; i < a.length; i++) {
if ((new RegExp(window.location.href)).test(a[i].href)) {
a[i].onclick = function () {
return false;

1.2.2 mouse movement

        mousemoveThe event type is a real-time response event. When the position of the mouse pointer changes (move at least one pixel), the MouseMove event will be triggered.

The sensitivity of this event response mainly refers to the moving speed of the mouse pointer and the speed of the browser following the new.

The following usage:

var box = document.getElementById('box'); = 'absolute'; = '200px'; = '200px'; = 'green';
var mx, my, ox, oy;

function e(event) {
if (!event) {
event = window.event; = event.srcElement;
event.layerX = event.offsetX;
event.layerY = event.offsetY;
} = event.pageX || event.clientX + document.body.scrollLeft; = event.pageY || event.clientY + document.body.scrollTop;
return event;

document.onmousedown = function (event) {
event = e(event);
o =;
ox = parseInt(o.offsetLeft);
oy = parseInt(o.offsetTop);
mx =;
my =;
document.onmousemove = move;
document.onmouseup = stop;

function move(event) {
event = e(event); = ox + - mx + 'px'; = oy + - my + 'px';

function stop(event) {
event = e(event);
ox = parseInt(o.offsetLeft);
oy = parseInt(o.offsetTop);
mx =;
my =;
o = document.onmousemove = document.onmouseup = null;

1.2.3 mouse passing

Mouse passes includeThere are two types of events:

Move over

When you move the mouse pointer over an element, the mouseover event is triggered.


When you move the mouse pointer out of an element, the mouseout event is triggered.

If you move from the parent element to the child element, the parent element will also be triggeredmouseoverEvent type.

The following usage:

var div = document.getElementsByTagName('div');
for (var i = 0; i < div.length; i++) {
div[i].onmousemove = function (e) { = 'orange'; = '24px'; = '600';
div[i].onmouseout = function () { = 'red';

1.3 keyboard events

Keyboard events are triggered when the user operates the keyboard.

Keyboard events mainly include the following three types


Triggered when a key is pressed on the keyboard.


Triggered when a keyboard key is pressed and released.


Triggered when a keyboard key is released.

1.3.1 keyboard event attributes

Keyboard events define many attributes, which can be used to accurately control keyboard operations. Keyboard event properties generally exist in the event object only when keyboard related events occur.

The following usage:

var box = document.getElementById('box'); = 'absolute'; = '100px'; = '100px'; = 'green';
document.keyDown = keyDown;
function keyDown(event) {
var event = event || window.event;
switch (event.keyCode) {
case 37: = box.offsetLeft - 5 + 'px';
case 38: = box.offsetLeft + 5 + 'px';
case 39: = box.offsetTop - 5 + 'px';
case 40: = box.offsetTop + 5 + 'px';
return false;

1.4 using page events

All page events explicitly handle the functions and states of the entire page.

1.4.1 window reset

The resize event type is triggered when the browser window is reset. The resize event can be triggered when the user adjusts the window size, or maximizes, minimizes or restores the window size display.

This time can be used to dynamically adjust the display size of page elements according to the change of window size.

The following usage:

var box = document.getElementById("box"); = "absolute"; = "red"; = w() * 0.8 + "px"; = h() * 0.8 + "px";
window.onresize = function () { = w() * 0.8 + "px"; = h() * 0.8 + "px";
function w() {
If (window. Innerwidth) {// DOM compatible
return window.innerWidth;
} else if (document.body) {
return document. body. clientWidth; // Compatible with IE
function h() {
if (window.innerHeight) {
return window.innerHeight;
} else if (document.body) {
return document.body.clientHeight;

1.4.2 page scrolling

The scroll event type is triggered when the element scroll bar scrolls.

The following usage:

    var box = document.getElementById("box"); = 'absolute'; = '100px'; = '100px'; = 'green';
        window.onload = f;
        window.onscroll = f;
        function f() {
   = 100 + parseInt(document.body.scrollLeft) + 'px';
   = 100 + parseInt(document.body.scrollTop) + 'px';

1.5 using UI events

UI events are responsible for responding to user interaction with page elements.

1.5.1 focus processing

Focus processing mainly includes the following two types of events:


Get focus


Lose focus

The so-called gaining focus; Is to activate the form field so that it can respond to keyboard events.

The so-called loss of focus: this event will be triggered when the specified element loses focus. (usually applied to form elements.)

The following usage:

var form = document.getElementById('myform');
var field = form.elements['name'];
window.onload = function () {

1.5.2 select text

When text is selected in a text box or text area, the select event is triggered.

The following usage:

var a = document.getElementsByTagName('input')[0];
var b = document.getElementsByTagName('input')[1];
a.onselect = function () {
if (document.selection) {
o = document.selection.createRange();
if (o.text.length > 0)
b.value = o.text;
} else {
p1 = a.selectionStart;
p2 = a.selectionEnd;
b.value = a.value.substring(p1, p2);

1.5.3 string change detection

The change event type is triggered when the value of a form element changes. It is mainly used for input, select, and textarea elements.

The following usage:

  var a = document.getElementsByTagName('select')[0];
        a.onchange = function () {
  , '');

1.5.4 submission form


The following usage:

var t = document.getElementsByTagName('input')[0];
var f = document.getElementsByTagName('form')[0];
f.onsubmit = function (e) {

1.5.5 reset form

When you click the reset button, the form is reset and all form fields return to their original values. The resct event is triggered.

The following usage:

var t = document.getElementsByTagName('input')[0];
var f = document.getElementsByTagName('form')[0];
f.onreset = function (e) {
1.5.6 clipboard data

HTML5 regulates the operation of clipboard data.

It mainly includes 6 clipboard events:


Triggered before a copy operation occurs.


Triggered when a copy operation occurs.


Triggered before the cutting operation occurs.


Triggered when a cut operation occurs.


Triggered before the paste operation occurs.


Triggered when a paste operation occurs.

As for copy, cut and paste events, all browsers will trigger them as long as the corresponding options are selected in the context menu.

The following usage:

var form = document.getElementById('myform');
var field1 = form.elements[0];
var getClipboardText = function (event) {
var clipboardData = (event.clipboardData || window.clipboardData);
return clipboardData.getData('text');
var setClipboardText = function (event, value) {
if (event.clipboardData) {
event.clipboardData.setData('text/plain', value);
} else if (window.clipboardData) {
window.clipboardData.setData('text', value);
var addHandler = function (element, type, handler) {
if (document.addEventListener) {
document.addEventListener(type, handler, false);
} else if (element.attachEvent) {
element.attachEvent('on' + type, handler);
} else {
element['on' + type] = handler;
addHandler(field1, 'paste', function (event) {
event = event || window.event;
var text = getClipboardText(event);
if (!/^\d*$/.text(text)) {
if (event.preventDefault) {
} else {
event.returnValue = false;

1.6 practical cases

1.6.1 design pop-up dialog box

Whether engaged in Web front-end development or Vue front-end development, events are often used.

The following usage:

function Dialog(id) { = id;
var that = this;
document.getElementById(id).children[0].onclick = function () {
} = function () {
var dlg = document.getElementById(; = 'block';
dlg = null;
Dialog.prototype.close = function () {
var dlg = document.getElementById(; = 'none';
dlg = null;
function openDialog() {
var dlg = new Dialog('dlgText');;