JavaScript window events

Table of contents

1. DOMContentLoaded: Triggered when the initial HTML document is fully loaded and parsed.

2. Load: Triggered when the entire page and all its resources (such as images and style sheets) complete loading.

3. beforeunload: Triggered before the window or frame is about to be unloaded. It is usually used to prompt the user whether to leave the current page.

4. unload: triggered after the window or frame has been unloaded.

5. resize: Triggered when the window or frame is resized.

6. scroll: Triggered when the scroll bar scrolls.


JavaScript provides a number of window (browser window) related events that can be used to detect and respond to the status and operations of the window.

1. DOMContentLoaded: Triggered when the initial HTML document is fully loaded and parsed.

The event DOMContentLoaded is triggered after the HTML document has been completely loaded and parsed, that is, the DOM tree is built and all HTML elements are accessible. The usage scenario of this event is usually to perform initialization operations, bind event handlers, or perform other DOM-related operations after the page is loaded.

Here is a simple example showing how to use the DOMContentLoaded event to perform some initialization operations:

<!DOCTYPE html>
<html>
<head>
  <title>DOM Content Loaded Example</title>
  <script>
    document.addEventListener('DOMContentLoaded', function(event) {
      // DOM内容加载完成后执行的操作
      var heading = document.querySelector('h1');
      heading.style.color = 'blue';
      heading.textContent = 'DOM Content Loaded';
    });
  </script>
</head>
<body>
  <h1>Example Heading</h1>
  <p>This is an example paragraph.</p>
</body>
</html>

In the above example, the DOMContentLoaded event listener will be triggered after the DOM content is loaded, and then modify the text content of the h1 element in the page to "DOM Content Loaded" and set its color to blue. This operation will be performed immediately when the page loads, without waiting for all resources (such as images) to be loaded.

By using the DOMContentLoaded event, you can ensure that the basic structure of the document is in place when handling DOM-related operations, providing a better user experience.

2. Load: Triggered when the entire page and all its resources (such as images and style sheets) complete loading.

The load event is triggered after the entire page and all its resources (such as images, style sheets, scripts, etc.) have been loaded. The usage scenario of this event is usually to perform some operations after the page is fully loaded, such as initializing the page content, binding event handlers, or performing other tasks related to the completion of page loading.

Here is a simple example showing how to use the load event to perform some operations:

<!DOCTYPE html>
<html>
<head>
  <title>Load Event Example</title>
  <script>
    window.addEventListener('load', function(event) {
      // 页面加载完成后执行的操作
      var heading = document.querySelector('h1');
      heading.style.color = 'red';
      heading.textContent = 'Page Loaded';
    });
  </script>
</head>
<body>
  <h1>Example Heading</h1>
  <p>This is an example paragraph.</p>
</body>
</html>

In the above example, the load event listener will be triggered after the entire page and all its resources are loaded, and then the text content of the h1 element in the page will be modified to "Page Loaded" and its color will be set to red.

By using the load event, you can ensure that all resources in the page have been loaded while handling tasks required after the page has completed loading, providing more complete and reliable operation.

3. beforeunload: Triggered before the window or frame is about to be unloaded. It is usually used to prompt the user whether to leave the current page.

The beforeunload event is triggered before the user leaves the current page. It can be used to perform some operations or provide a confirmation prompt before the user closes or navigates away from the page to ensure the user's intention.

Here is a simple example showing how to use the beforeunload event to provide a confirmation prompt:

<!DOCTYPE html>
<html>
<head>
  <title>Beforeunload Event Example</title>
  <script>
    window.addEventListener('beforeunload', function(event) {
      // 提示用户确认离开页面
      event.returnValue = 'Are you sure you want to leave this page?';
    });
  </script>
</head>
<body>
  <h1>Example Heading</h1>
  <p>This is an example paragraph.</p>
</body>
</html>

In the above example, the beforeunload event listener is triggered before the user closes or navigates away from the page, and the event.returnValue property is set to use a string as the confirmation prompt. When the user attempts to close or leave the page, the browser will pop up a dialog box, display a prompt message, and provide the option to confirm or cancel.

Using the beforeunload event, you can ask the user if they are sure before they close or navigate away from the page to prevent accidentally leaving or losing unsaved changes. Please note that due to browser security restrictions, you cannot perform blocking operations in the beforeunload event, but you can display a confirmation prompt to the user.

4. unload: triggered after the window or frame has been unloaded.

The unload event is triggered when the user leaves the current page and can be used to perform some cleanup operations or provide additional prompts to ensure that the user has a correct experience at the last moment before leaving the page.

Here is a simple example showing how to use the unload event to perform some operations:

<!DOCTYPE html>
<html>
<head>
  <title>Unload Event Example</title>
  <script>
    window.addEventListener('unload', function(event) {
      // 执行清理操作或提供额外的提示
      alert('Are you sure you want to leave this page?');
    });
  </script>
</head>
<body>
  <h1>Example Heading</h1>
  <p>This is an example paragraph.</p>
</body>
</html>

In the above example, the unload event listener will be triggered when the user leaves the current page, and then display an alert box asking the user if they are sure to leave the page.

Using the unload event, you can perform necessary actions before the user leaves the page, such as saving user data, cleaning up resources, or providing additional confirmation. Please note that due to browser security restrictions, you cannot perform blocking operations or cancel navigation in the unload event, but you can display some prompt information to the user.

5. resize: Triggered when the window or frame is resized.

The event resize is triggered when the window size changes and can be used to respond to window size changes and perform corresponding operations. This event is typically used to adjust page layout or recalculate element dimensions to accommodate different window sizes.

Here is a simple example showing how to use the resize event to adjust the page layout:

<!DOCTYPE html>
<html>
<head>
  <title>Resize Event Example</title>
  <style>
    .container {
      width: 100%;
      height: 100vh;
      display: flex;
      justify-content: center;
      align-items: center;
      background-color: lightblue;
    }
    
    .content {
      font-size: 24px;
      padding: 20px;
      background-color: white;
      border: 2px solid black;
    }
  </style>
  <script>
    window.addEventListener('resize', function() {
      // 当窗口大小改变时,调整页面布局
      var container = document.querySelector('.container');
      var content = document.querySelector('.content');
      container.style.height = window.innerHeight + 'px';
      content.textContent = 'Window width: ' + window.innerWidth + 'px, height: ' + window.innerHeight + 'px';
    });
  </script>
</head>
<body>
  <div class="container">
    <div class="content">Window width: 0px, height: 0px</div>
  </div>
</body>
</html>

In the above example, the resize event listener will be triggered when the window size changes and call the function to adjust the page layout. When the window size changes, the container elements in the page adjust to the new size of the window and update the width and height of the display window.

Using the resize event, you can implement responsive layout so that the page can adapt to windows of different sizes and handle accordingly when the window size changes. This is very useful when developing responsive web pages or applications.

6. scroll: Triggered when the scroll bar scrolls.

The scroll event is triggered when the page scrolls and can be used to listen to page scroll events and perform corresponding operations. This event is usually used to achieve scrolling effects, lazy loading of content, or real-time monitoring of the scroll position.

The following is a simple example that shows how to use the scroll event to achieve scrolling effects:

<!DOCTYPE html>
<html>
<head>
  <title>Scroll Event Example</title>
  <style>
    body {
      height: 2000px;
    }
    
    .header {
      position: fixed;
      top: 0;
      left: 0;
      width: 100%;
      background-color: lightblue;
      padding: 20px;
      text-align: center;
      font-size: 24px;
      box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
    }
    
    .content {
      margin-top: 100px;
      text-align: center;
      font-size: 18px;
      color: gray;
    }
  </style>
  <script>
    window.addEventListener('scroll', function() {
      // 监听页面滚动事件
      var header = document.querySelector('.header');
      var content = document.querySelector('.content');
      
      if (window.scrollY > 100) {
        // 当滚动超过100像素时,添加特定样式
        header.classList.add('scrolled');
        content.textContent = 'Scrolling...';
      } else {
        // 当滚动小于等于100像素时,移除特定样式
        header.classList.remove('scrolled');
        content.textContent = 'Keep scrolling...';
      }
    });
  </script>
</head>
<body>
  <div class="header">
    Header
  </div>
  
  <div class="content">
    Keep scrolling...
  </div>
</body>
</html>

In the above example, the scroll event listener will be triggered when the page is scrolled and change the style of the page elements based on the scroll position. When the page scrolls beyond 100 pixels, a specific class name is added to the header element and the corresponding text content is updated to display.

By using the scroll event, you can achieve various scrolling-related effects, such as fixed navigation bar, lazy loading of content, infinite scrolling, etc. This event provides the ability to interact with page scrolling, allowing you to trigger different actions and style changes based on the scroll position.

Guess you like

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