jQuery window resize

Filed Under: jQuery

jQuery resize() function triggers when the browser window is resized. jQuery resize function attaches a handler, which executes when the resize event is fired.

jQuery resize

The syntax for using jQuery resize():

  • resize()

This signature is used without any arguments. This function is shortcut for .trigger( "resize" ) function.

  • resize(handler)

The handler is a function, which is executed when the browser window is resized.

  • resize(eventData, handler)

eventData is the object that will be passed to the event handler.

jQuery resize method is a shortcut for .on('resize', handler) in the second and third variations.

jQuery window resize

Following example demonstrates jQuery window resize event.


<!DOCTYPE html>
<html>
<head>
<title>jQuery Resize</title>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<style>
p {
color: green;
}
div {
width: 80px;
height: 80px;
float: left;
padding: 10px;
margin: 10px;
background-color: yellow;
}
</style>
<script>
var x=0;
$(document).ready(function(){
  $(window).resize(function(){
    $("span").text(x++);
  });
});
</script>
</head>
<body>

<p>Change your window size</p>
<div>Resized <b> <span>0</span></b> times.</div>

</body>
</html>

In this example, you can see that the jQuery resize() function is triggered when you change the size of the browser window.

The handler attached to the resize() method executes and you can see the count of this event displayed in the <div> element.

Note that resize() method will not execute if your HTML page is embedded using iframe, since you are changing the main window size not the iframe size. You can see it in action by visiting below demo page.

jQuery resize() event demo

Reference: API Doc

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages