×

jQuery Tutorial

jQuery Examples

jQuery Practice

jQuery on window resize

In this tutorial, we will discuss about window resize in jQuery and method used for it.
Submitted by Pratishtha Saxena, on July 08, 2022

We can keep a check when the window is being resized from its default size. There are many times that window size has to be kept in mind like making games or some other applications, that are dependent on the window size then it is important to know when the user changes the window's default size.

For this specific task, jQuery has a method called resize(). This method initializes or triggers whenever the window size changes. When this method triggers, basically a function that is attached to it gets implemented.

Syntax:

$(selector).resize(function);

We can also count the number of times the window has been resized. This can be done by declaring a variable initially equal to 0. Then each time the function of resize() method initializes, the variable can be incremented by 1 which will return the number of times the window has been resized.

Example:

HTML:

<!DOCTYPE html>

<html>
   <head>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
   </head>
   
   <body>
      <center>
         <h2>Change the Window Size.</h2>
         <p>Window has been resized: 
         <div>0</div>
         </p>
      </center>
   </body>
   
</html>

jQuery Function:

<script>
var a = 0;
$(document).ready(function(){
  $(window).resize(function(){
    $("div").text(a += 1);
  });
});
</script>

Output:

Initially:

Example 1: on window resize

After Resizing the Window:

Example 2: on window resize





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.