jQuery Document and Window events detail guide with example

Updated on ... 01st March 2023

jQuery provides a way to bind functions to several Document/Window events, which are triggered when certain actions are performed on the page. These events can be used to add interactivity to web pages and perform actions in response to user actions.

However, jQuery provides both window and document events, and they serve different purposes.

Window events are triggered by actions performed on the browser window, such as resizing or scrolling, while document events are triggered by actions performed on the HTML document, such as clicking or submitting a form.

Here are some examples of common window events:

  • $(window).load()
  • $(window).resize()
  • $(window).scroll()
  • $(window).unload()
  • $(window).error()
  • $(window).beforeunload()
  • $(window).hashchange()
  • $(window).focus()
  • $(window).blur()

jQuery $(window).load() event

$(window).load(): This event is triggered when all page assets, including images, scripts, and stylesheets, have finished loading. This event can be used to perform tasks that require all page assets to be available.

The $(window).load() event can be helpful for performing tasks that require all the assets on the page to be fully loaded, such as initializing plugins, setting up animations, or loading dynamic content.

Example:


                                                    

                                                    

                                                    $(window).load(function() {
  // Code to be executed after the page has fully loaded
});

                                                    

                                                

It's worth noting that the $(window).load() event has been deprecated as of jQuery 3.0. Instead, you can use the $(window).on('load', function() {}) syntax to achieve the same effect.

jQuery $(window).resize() event

The $(window).resize() event in jQuery is triggered when the browser window is resized. This event can be useful for adjusting the layout or behavior of a web page in response to changes in the window size.

Here's a basic example of the $(window).resize() event in jQuery:


                                                    

                                                    

                                                    $(window).resize(function() {
  // Code to be executed when the window is resized
});

                                                    

                                                

You Should Also Read

Here's an example of how to use the $(window).resize() event to adjust the font size of a heading element in response to changes in the window size:


                                                    

                                                    

                                                    <!DOCTYPE html>
<html>
<head>
  <title>Window Resize Example</title>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <style>
    h1 {
      font-size: 2em;
    }
  </style>
  <script>
    $(window).resize(function() {
      var windowWidth = $(window).width();
      if (windowWidth <= 600) {
        $('h1').css('font-size', '1.5em');
      } else {
        $('h1').css('font-size', '2em');
      }
    });
  </script>
</head>
<body>
  <h1>This is Heading size will change on window resize</h1>
</body>
</html>

                                                    

                                                

jQuery $(window).scroll() event

The $(window).scroll() event in jQuery is triggered when the user scrolls the page. This event can be useful for creating dynamic effects or triggering actions as the user scrolls through a web page.

Basic Example:


                                                    

                                                    

                                                    $(window).scroll(function() {
  // Code to be executed when the user scrolls the page
});

                                                    

                                                

Here's an example of how to use the $(window).scroll() event to create a "scroll to top" button that appears when the user scrolls down the page:


                                                    

                                                    

                                                    <!DOCTYPE html>
<html>
<head>
  <title>Scroll Event Example</title>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <style>
    #scroll-to-top {
      display: none;
      position: fixed;
      bottom: 20px;
      right: 20px;
      font-size: 16px;
      background-color: #333;
      color: #fff;
      border-radius: 50%;
      width: 40px;
      height: 40px;
      text-align: center;
      line-height: 40px;
    }
  </style>
  <script>
    $(window).scroll(function() {
      if ($(this).scrollTop() > 100) {
        $('#scroll-to-top').fadeIn();
      } else {
        $('#scroll-to-top').fadeOut();
      }
    });

    $('#scroll-to-top').click(function() {
      $('html, body').animate({scrollTop : 0},800);
      return false;
    });
  </script>
</head>
<body>
  <h1>Scroll Event Example</h1>
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla eu nibh ac nisl rutrum facilisis.</p>
  <p>Sed pharetra velit non ipsum lacinia commodo. Suspendisse bibendum libero sit amet ante tempor euismod.</p>
  <p>In eget lacus ut nisi convallis euismod eget ut leo. Duis ut erat a odio convallis laoreet.</p>
  <p>In ultrices nulla nec erat pretium, id blandit neque lobortis. Donec sit amet tortor lacinia, luctus nisl eu, convallis urna.</p>
  <button id="scroll-to-top">Top</button>
</body>
</html>

                                                    

                                                

jQuery $(window).unload() event

The $(window).unload() event in jQuery is triggered just before the browser window is unloaded, either by the user closing the window or navigating away from the page.

Note that the $(window).unload() event is not supported in some browsers, including Google Chrome lower version and Safari's lower version.  However, all the latest versions of browsers supported it.

Basic example:


                                                    

                                                    

                                                    $(window).unload(function() {
  // Code to be executed when the window is unloaded
});

                                                    

                                                

Here's a more specific example of how to use the $(window).unload() event to show a confirmation dialog when the user tries to leave the page without saving their changes:


                                                    

                                                    

                                                    <!DOCTYPE html>
<html>
<head>
  <title>Unload Event Example</title>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script>
    var unsavedChanges = false;

    $('input[type="text"]').on('input', function() {
      unsavedChanges = true;
    });

    $(window).unload(function() {
      if (unsavedChanges) {
        return 'You have unsaved changes. Are you sure you want to leave the page?';
      }
    });
  </script>
</head>
<body>
  <h1>Unload Event Example</h1>
  <p>Type something in the text field below to simulate unsaved changes:</p>
  <input type="text" />
</body>
</html>

                                                    

                                                

jQuery $(window).error() event

The $(window).error() event in jQuery is triggered when an error occurs while loading a resource such as an image, script, or stylesheet.

Note that this event is deprecated as of jQuery 3.6 and should be replaced with the $(window).on('error') syntax instead.

Basic example:


                                                    

                                                    

                                                    $(window).on('error', function(event) {
  console.log('An error occurred:', event);
});

                                                    

                                                

Here's an example of how to use the $(window).on('error') event in jQuery:


                                                    

                                                    

                                                    <!DOCTYPE html>
<html>
<head>
  <title>Error Event Example</title>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script>
    $(window).on('error', function(event) {
      alert('An error occurred while loading a resource!' : event);
    });
  </script>
</head>
<body>
  <h1>Error Event Example</h1>
  <img src="https://example.com/non-existent-image.png" />
</body>
</html>

                                                    

                                                

Related Post

Leave a comment