Several uncommon binding events in JavaScript

Table of contents

1. fullscreenchange event

2. Pagehide event

3. pageshow event

4. Hashchange event

5. Online events

6. Offline events

7. popstate event

8. devicemotion event

9. deviceorientation event


1. fullscreenchange event

The fullscreenchange event is a browser event that fires when an element enters or exits full-screen mode. It provides a way to detect changes in full-screen state and can be used to perform appropriate actions or update the user interface in full-screen mode.

The fullscreenchange event is triggered when the user switches the browser window to full-screen mode using the full-screen function (for example, pressing the F11 key), or when the specified element is switched to full-screen mode by calling the full-screen API (for example, requestFullscreen()) through JavaScript.

At the same time, when the user exits full-screen mode, or calls the full-screen API through JavaScript to exit an element from full-screen mode, the fullscreenchange event will also be triggered.

Sample code looks like this:

document.addEventListener("fullscreenchange", function(event) {
  if (document.fullscreenElement) {
    // 元素进入全屏模式
    console.log("进入全屏模式");
    // 执行相应的操作或更新界面
  } else {
    // 元素退出全屏模式
    console.log("退出全屏模式");
    // 执行相应的操作或更新界面
  }
});

2. Pagehide event

The `pagehide` event is a browser event that is fired when a page is hidden. It is part of the page unloading process and is triggered when the user leaves the current tab or closes the browser. By listening to the `pagehide` event, you can capture when the user leaves the page and perform appropriate actions.

The `pagehide` event is similar to the `unload` event, but there are some differences. The main difference is that the `pagehide` event is a cancelable event, which means that the page can be prevented from being hidden by canceling the event's default behavior. In contrast, the `unload` event is not cancelable, and the unloading of the page cannot be prevented.

The following is the basic flow of using the `pagehide` event:

1. Use the `addEventListener` method to bind the `pagehide` event to the `window` object or `document` object.
2. In the event handler, you can perform operations that need to be performed when the page is hidden, such as saving unsaved data, sending statistical information, etc.
3. If you need to prevent the page from being hidden, you can call the `preventDefault()` method of the event object.

Sample code looks like this:

window.addEventListener("pagehide", function(event) {
  // 执行页面隐藏时的操作
  console.log("页面即将隐藏");
  
  // 如果需要阻止页面的隐藏,取消事件的默认行为
  event.preventDefault();
});

It should be noted that since the page has been hidden when the `pagehide` event occurs, the operations performed in the event handler should be lightweight to avoid affecting the user experience.

By using the `pagehide` event, you can capture the moment before the user leaves the page and take appropriate action if necessary. This is useful for saving data, cleaning resources, sending statistics, etc.

3. pageshow event

The `pageshow` event is a browser event that is fired when a page is shown. It is part of the page loading and display process and is triggered when the user opens a new tab, navigates back to the current tab, or refreshes the page. The `pageshow` event provides a way to capture the timing of a page being displayed and perform corresponding operations.

The `pageshow` event is different from the `DOMContentLoaded` and `load` events in that it fires when the page is displayed, not when the page is fully loaded or when the DOMContentLoaded event fires.

The following is the basic flow of using the `pageshow` event:

1. Use the `addEventListener` method to bind the `pageshow` event to the `window` object or `document` object.
2. In the event handler, you can perform operations that need to be performed when the page is displayed, such as restoring state, loading data, etc.

Sample code looks like this:

window.addEventListener("pageshow", function(event) {
  // 执行页面展示时的操作
  console.log("页面已展示");
});

It should be noted that the `pageshow` event is also triggered when the page is refreshed. Therefore, the actions performed in the event handler should be repeatable to ensure that they work properly when the page is refreshed.

By using the `pageshow` event, you can capture the moment when a page is displayed and perform appropriate actions. This is useful for restoring state, loading data, or performing other operations related to page presentation.

4. Hashchange event

The `hashchange` event is a browser event that is fired when the URL's fragment identifier (i.e. hash value) changes. The fragment identifier is the part of the URL that follows the `#` symbol. The `hashchange` event provides a way to listen for changes in the URL hash value so that appropriate actions can be performed when the hash value changes.

In web applications, URL fragment identifiers are often used to implement front-end routing or page state management. The `hashchange` event is triggered when the user clicks a link within the page or performs other operations that cause the hash value of the URL to change.

The following is the basic flow of using the `hashchange` event:

1. Use the `addEventListener` method to bind the `hashchange` event to the `window` object.
2. In the event handler, you can get the current hash value through the `location.hash` property and perform corresponding operations.

Sample code looks like this:

window.addEventListener("hashchange", function(event) {
  // 获取当前的哈希值
  var newHash = location.hash;
  
  // 执行相应的操作,例如根据哈希值加载不同的内容或触发前端路由逻辑
  console.log("哈希值发生变化:" + newHash);
});

By listening to the `hashchange` event, you can obtain changes in the URL hash value in real time and perform corresponding operations as needed, such as updating page content, switching views, or performing front-end routing navigation.

It should be noted that the `hashchange` event can only monitor changes in the URL hash value, but cannot monitor changes in other URLs (such as protocol, domain name, path, etc.). For listening to changes in the entire URL, you can use the `popstate` event and the History API.

5. Online events

The `online` event is a browser event that is triggered when the device's network connection status changes from offline to online. It is used to detect the network connection status of the device and perform appropriate actions when the device reconnects to the network.

When the device is offline (no network connection), if the network connection is restored, the browser will trigger the `online` event to notify the JavaScript code that the device has reconnected to the network.

The following is the basic flow of using `online` events:

1. Use the `addEventListener` method to bind the `online` event to the `window` object.
2. In the event handler, you can perform operations that need to be performed when the device reconnects to the network, such as loading data, sending requests, etc.

Sample code looks like this:

window.addEventListener("online", function(event) {
  // 设备已重新连接到网络
  console.log("设备已在线");
});

By listening to the `online` event, you can capture the opportunity when the device reconnects to the network and take appropriate actions. This is useful for caching data while offline or alerting the user that the device has reconnected to the network.

It should be noted that the `online` event can only detect the status change of the device from offline to online, and cannot detect whether the device remains online. If you need to detect the online status of the device, you can use the `navigator.onLine` property. When `navigator.onLine` is `true`, it means that the device is currently online; when it is `false`, it means that the device is currently offline.

6. Offline events

The `offline` event is a browser event that is triggered when the device's network connection status changes from online to offline. It is used to detect the network connection status of the device and perform appropriate actions when the device disconnects from the network.

When the device is online (with a network connection), if the network connection is interrupted, the browser will trigger the `offline` event to notify the JavaScript code that the device is offline.

The following is the basic flow of using the `offline` event:

1. Use the `addEventListener` method to bind the `offline` event to the `window` object.
2. In the event handler, you can perform operations that need to be performed when the device disconnects from the network, such as displaying offline status prompts, pausing data upload, etc.

Sample code looks like this:

window.addEventListener("offline", function(event) {
  // 设备已离线
  console.log("设备已离线");
});

By listening to the `offline` event, you can capture the opportunity when the device disconnects from the network and perform appropriate actions. This is useful if data needs to be processed offline or to alert the user that the device has been disconnected from the network.

It should be noted that the `offline` event can only detect the status change of the device from online to offline, and cannot detect whether the device remains offline. If you need to detect the online status of the device, you can use the `navigator.onLine` property. When `navigator.onLine` is `true`, it means that the device is currently online; when it is `false`, it means that the device is currently offline.

7. popstate event

The `popstate` event is a browser event in JavaScript that is triggered when the browser's history (that is, a URL modified through `history.pushState()` or `history.replaceState()`) changes.

Usually, it is triggered when the user clicks the browser's forward or back button, or when the `history.back()`, `history.forward()`, `history.go()` methods are called through JavaScript to cause the history to change. `popstate` event.

The `popstate` event provides an opportunity for developers to perform actions when the browser's history changes. For example, you can use the `popstate` event to update page content, refresh data, or perform other actions related to URL changes.

The following is the basic flow of using the `popstate` event:

1. Use the `addEventListener` method to bind the `popstate` event to the `window` object.
2. In the event handler, you can perform operations related to URL changes as needed.

Sample code looks like this:

window.addEventListener("popstate", function(event) {
  // 历史记录发生变化
  console.log("历史记录变化");
  // 执行其他操作,如更新页面内容或刷新数据
});

Note that the `popstate` event is not fired when the page is first loaded. This event is only fired when the page has loaded and a history change has occurred.

In addition, history can be modified and the `popstate` event triggered by calling `history.pushState()`, `history.replaceState()` or the browser's forward/back buttons. However, be careful to avoid calling these methods again in the `popstate` event handler to avoid causing an infinite loop.

8. devicemotion event

The `devicemotion` event is a device event in JavaScript that is triggered when the physical motion state of the device changes. This event provides relevant information such as the acceleration and rotation rate of the device, and is used to detect the motion status of the device.

When a device moves, rotates, or undergoes other physical motion, such as shaking, rotating the device, or tilting the device on a mobile device, the browser generates a `devicemotion` event and passes relevant data to the event handler.

The `devicemotion` event object contains the following properties:

- `acceleration`: represents the acceleration of the device, expressed in the form of three-dimensional coordinates, that is `{ x: number, y: number, z: number }`.
- `accelerationIncludingGravity`: Indicates the total acceleration including gravity acceleration, expressed in three-dimensional coordinates.
- `rotationRate`: Indicates the rotation rate of the device, expressed in three-dimensional coordinates, that is `{ alpha: number, beta: number, gamma: number }`.
- `interval`: Indicates the time interval between generating `devicemotion` events.

The following is the basic flow of using the `devicemotion` event:

1. Use the `addEventListener` method to bind the `devicemotion` event to the `window` object.
2. In the event handler, you can obtain information such as the acceleration and rotation rate of the device through properties such as `event.acceleration`, `event.accelerationIncludingGravity` and `event.rotationRate`, and perform corresponding operations.

Sample code looks like this:

window.addEventListener("devicemotion", function(event) {
  // 获取设备的加速度信息
  var acceleration = event.acceleration;
  var accelerationIncludingGravity = event.accelerationIncludingGravity;
  
  // 获取设备的旋转速率信息
  var rotationRate = event.rotationRate;
  
  // 执行其他操作,如根据加速度进行某些动作或旋转等
});

It should be noted that the `devicemotion` event may be triggered frequently, and the specific triggering frequency depends on the device and browser implementation. When processing events, you can choose the appropriate method to throttle or filter as needed to avoid triggering too frequently and affecting performance.

Additionally, the `devicemotion` event requires device support and user authorization to be used. On mobile devices, the user is typically required to allow the browser to access the device's motion sensors.

9. deviceorientation event

The `deviceorientation` event is a device event in JavaScript that is triggered when the device's orientation changes. This event provides the device's orientation information, including the device's tilt, rotation, and azimuth.

When a device rotates, tilts, or changes orientation, such as changing the device's orientation or rotating the device on a mobile device, the browser generates a `deviceorientation` event and passes the relevant data to the event handler.

The `deviceorientation` event object contains the following properties:

- `alpha`: Indicates the rotation angle of the device around the z-axis, ranging from 0 to 360 degrees.
- `beta`: Indicates the tilt angle of the device around the x-axis, ranging from -180 to 180 degrees.
- `gamma`: Indicates the tilt angle of the device around the y-axis, ranging from -90 to 90 degrees.
- `absolute`: Indicates whether the device direction information is an absolute value. If `true`, it means that absolute direction information is provided; if `false`, it means that relative direction information is provided.

The following is the basic flow of using the `deviceorientation` event:

1. Use the `addEventListener` method to bind the `deviceorientation` event to the `window` object.
2. In the event handler, you can obtain the orientation information of the device through properties such as `event.alpha`, `event.beta` and `event.gamma` and perform corresponding operations.

Sample code looks like this:

window.addEventListener("deviceorientation", function(event) {
  // 获取设备的方向信息
  var alpha = event.alpha;
  var beta = event.beta;
  var gamma = event.gamma;
  
  // 执行其他操作,如根据方向信息调整页面布局或进行相应的动作等
});

It should be noted that the `deviceorientation` event may be triggered frequently, and the specific triggering frequency depends on the device and browser implementation. When processing events, you can choose the appropriate method to throttle or filter as needed to avoid triggering too frequently and affecting performance.

In addition, the `deviceorientation` event requires device support and user authorization to be used. On mobile devices, the user is typically required to allow the browser to access the device's orientation sensor.

Guess you like

Origin blog.csdn.net/zhangawei123/article/details/130930135