Thursday, October 16, 2025
HomeLanguagesJavascriptCross-browser window resize event using JavaScript/jQuery

Cross-browser window resize event using JavaScript/jQuery

The resize() method is an inbuilt method in jQuery that is used when the browser window changes its size. The resize() method triggers the resize event or attaches a function to run when a resize event occurs. jQuery has a built-in method for window resizing events. 

Syntax: 

$(selector).resize(function)

This syntax is used for cross-browser resize events. 

Example 1: This example uses resize() method to count how many times browsers window resize. 

html




</script>
<script>
    var x = 1;
    $(document).ready(function() {
        $(window).resize(function() {
            $("span").text(x += 1);
        });
    });
</script>
<p>Window resized <span>0</span> times.</p>
<p>Try resizing your browser window.</p>


Output: 

 

You can use the addEventListener() method to register an event handler to listen for the browser window resize event, such as window.addEventListener(‘resize’, …). 

Syntax: 

object.addEventListner("resize", myscript);

Example 2: This example display the size of resize windows. 

html




<div id="result"></div>
  
<script>
    // Defining event listener function
    function displayWindowSize() {
          
        // Get width and height of the window
        // excluding scrollbars
        var w = document.documentElement.clientWidth;
        var h = document.documentElement.clientHeight;
      
        // Display result inside a div element
        document.getElementById("result").innerHTML
            = "Width: " + w + ", " + "Height: " + h;
    }
      
    // Attaching the event listener function
    // to window's resize event
    window.addEventListener("resize", displayWindowSize);
      
    // Calling the function for the first time
    displayWindowSize();
</script>
  
<p>
    <strong>Note:</strong> Please resize the browser
    window to see how it works.
</p>


Output: 

 

RELATED ARTICLES

Most Popular

Dominic
32361 POSTS0 COMMENTS
Milvus
88 POSTS0 COMMENTS
Nango Kala
6728 POSTS0 COMMENTS
Nicole Veronica
11892 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11953 POSTS0 COMMENTS
Shaida Kate Naidoo
6852 POSTS0 COMMENTS
Ted Musemwa
7113 POSTS0 COMMENTS
Thapelo Manthata
6805 POSTS0 COMMENTS
Umr Jansen
6801 POSTS0 COMMENTS