Javatpoint Logo
Javatpoint Logo

JavaScript onresize event

The onresize event in JavaScript generally occurs when the window has been resized. To get the size of the window, we can use the JavaScript's window.outerWidth and window.outerHeight events. We can also use the JavaScript's properties such as innerWidth, innerHeight, clientWidth, ClientHeight, offsetWidth, offsetHeight to get the size of an element.

In HTML, we can use the onresize attribute and assign a JavaScript function to it. We can also use the JavaScript's addEventListener() method and pass a resize event to it for greater flexibility.

Syntax

Now, we see the syntax of using the onresize event in HTML and in javascript (without addEventListener() method or by using the addEventListener() method).

In HTML

In JavaScript

In JavaScript by using the addEventListener() method

Let's see some of the illustrations to understand the onresize event.

Example

In this example, we are using the HTML onresize attribute. Here, we are using the window.outerWidth and window.outerHeight events of JavaScript to get the height and width of the window.

When the user resizes the window, the updated width and height of the window will be displayed on the screen. It will also display how many times the user tried to resize the window. When we change the height of the window, the updated height will change accordingly. Similarly, when we change the width of the window, the updated width will change accordingly.

Test it Now

Output

After the execution of the above code, the output will be -

JavaScript onresize event

When we try to resize the window, the output will be -

JavaScript onresize event

Example - Using JavaScript

In this example, we are using JavaScript's onresize event.

Test it Now

Output

After the execution of the above code, the output will be -

JavaScript onresize event

When we try to resize the window, the output will be -

JavaScript onresize event

Example - Using addEventListener() method

In this example, we are using JavaScript's addEventListener() method.

Test it Now

Output

After the execution of the above code, the output will be -

JavaScript onresize event

When we try to resize the window, the output will be -

JavaScript onresize event
Next TopicException Handling




Youtube For Videos Join Our Youtube Channel: Join Now

Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA