SoFunction
Updated on 2025-04-13

js actual case

is a method in JavaScript to use to specify objects (in this casewindowObject, representing a browser window) adds an event listener to execute the corresponding function (called an event handler or event listener) when a specific event occurs on that object.

This method accepts three parameters:

  • Event type (type): A string representing the type of event to be listened to. For example,"click"Indicates the mouse click event,"load"Indicates that the page loading is completed, etc.
  • Event handling function (listener): The function to be called when an event occurs. This function will receive an event object as a parameter, which contains all the information of the event, such as the element that triggers the event, event type, etc.
  • Use captured or bubbling boolean values ​​(options/useCapture)(Optional): A Boolean value that specifies whether the event is executed in the capture stage or in the bubble stage. The default value isfalse, indicating execution in the bubble stage.
  • In the DOM event stream, the event first goes through the capture phase, then reaches the target element, and finally goes through the bubble phase. If you want the event to fire during the capture phase, you can set this parameter totrue

Example

The following is a useAn example of listening to page loading completion events:

('load', function() {
    ('The page is loading!  ');
});

In this example, when the page is loaded (i.e. after all resources such as images, style sheets, etc. are loaded and parsed), the console will output"The page is loading!"

Remove event listener

If you want to remove the previously added event listener at some point, you can useremoveEventListenermethod. However, it is important to note that you have to provide the exact same function reference as when adding the listener, becauseremoveEventListenerThe listener is removed by reference matching.

Things to note

  • If the same listener is added multiple times for the same event, these listeners will be called.
  • useaddEventListenerAdded event listener, need to be usedremoveEventListenerto remove manually, otherwise they will remain until the page is uninstalled.
  • In useaddEventListenerWhen trying to avoid global scope (such as directly in<script>event handler functions are defined in the tags, because doing so increases pollution to the global namespace and may make it difficult for functions to be removed if needed. Instead, a function expression or arrow function should be used to define the event handling function.

Of course, here are some usagesThese cases will help you better understand the application of this method in actual development.

Example 1. Listen to the page loading completion event

When the page is fully loaded (including all dependencies such as images, style sheets, etc.), you may want to perform some initialization operations, such as sending statistics, initializing UI components, etc. At this time, you can useCome and listenloadevent.

('load', function() {
    ('The page is loaded and the initialization operation can be performed!  ');
    // Execute the initialization operation here});

Example 2. Listen to window size change events

In responsive web design, you may need to adjust the layout or style according to the size of the window. At this time, you can useCome and listenresizeevent.

('resize', function() {
    ('The window size has changed!  ');
    // Here you can adjust the layout or style according to the window size    // For example: Adjust the width of an element to 80% of the window width    ('myElement'). =  * 0.8 + 'px';
});

Example 3. Listening to scroll events

When the user scrolls the page, you may want to perform some actions, such as showing or hiding the navigation bar, loading more content, etc. At this time, you can useCome and listenscrollevent.

('scroll', function() {
    ('The page is scrolling!  ');
    // Perform operations according to the scroll position here    // For example: When scrolling to a certain position, the "Back to Top" button is displayed.    if ( &gt; 100) {
        ('backToTop'). = 'block';
    } else {
        ('backToTop'). = 'none';
    }
});

Example 4. Listen to changes in online/offline status

When developing applications that need to handle network status, you may want to know if the user is online. At this time, you can useCome and listenonlineandofflineevent.

('online', function() {
    ('The user is already online!  ');
    // Perform the required actions when online here});
('offline', function() {
    ('The user is offline!  ');
    // Perform the required actions when offline here});

Example 5. Listening to keyboard events

AlthoughUsually used to listen for window-related events, but you can also use it to listen for keyboard events, such askeydownkeyupwait. However, it is more common to add these event listeners to specific elements, but for demonstration purposes, here is a way to show how to use it.windowListen to keyboard events.

('keydown', function(event) {
    ('Pressed the key on the keyboard:', );
    // Here, perform the operation according to the pressed key    // For example: execute an action when the user presses the Enter key    if ( === 'Enter') {
        ('The user pressed the Enter key!  ');
    }
});

What is js here? That’s all for the article. For more related js content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!