JavaScript Window Resize Event

How to Capture Browser Window Resize Event in JavaScript

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

The following example will display the current width and height of the browser window on resize.

Example

        

Note: Please resize the browser window to see how it works.

You should avoid using the solution like window.onresize = function(event) < . >; , since it overrides the window.onresize event handler function. You should better assign a new event handler to the resize event using event listener, as shown in the example above.

Please check out the tutorial on JavaScript event listeners to learn more about it.

Here are some more FAQ related to this topic:

Источник

Window: resize event

The resize event fires when the document view (window) has been resized.

This event is not cancelable and does not bubble.

In some earlier browsers it was possible to register resize event handlers on any HTML element. It is still possible to set onresize attributes or use addEventListener() to set a handler on any element. However, resize events are only fired on the window object (i.e. returned by document.defaultView ). Only handlers registered on the window object will receive resize events.

While the resize event fires only for the window nowadays, you can get resize notifications for other elements using the ResizeObserver API.

If the resize event is triggered too many times for your application, see Optimizing window.onresize to control the time after which the event fires.

Syntax

Use the event name in methods like addEventListener() , or set an event handler property.

addEventListener("resize", (event) => >); onresize = (event) => >; 

Event type

Event properties

This interface also inherits properties of its parent, Event . UIEvent.detail Read only Returns a long with details about the event, depending on the event type. UIEvent.sourceCapabilities Experimental Read only Returns an instance of the InputDeviceCapabilities interface, which provides information about the physical device responsible for generating a touch event. UIEvent.view Read only Returns a WindowProxy that contains the view that generated the event. UIEvent.which Deprecated Non-standard Read only Returns the numeric keyCode of the key pressed, or the character code ( charCode ) for an alphanumeric key pressed.

Examples

Window size logger

HTML

p>Resize the browser window to fire the code>resizecode> event.p> p>Window height: span id="height">span>p> p>Window width: span id="width">span>p> 

JavaScript

const heightOutput = document.querySelector("#height"); const widthOutput = document.querySelector("#width"); function reportWindowSize()  heightOutput.textContent = window.innerHeight; widthOutput.textContent = window.innerWidth; > window.onresize = reportWindowSize; 

Result

addEventListener equivalent

.addEventListener("resize", reportWindowSize); 

Specifications

Browser compatibility

Found a content problem with this page?

This page was last modified on Apr 8, 2023 by MDN contributors.

Your blueprint for a better internet.

MDN

Support

Our communities

Developers

Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.

Источник

Событие изменения размера окна в JavaScript

Событие изменения размера окна в JavaScript

  1. Добавить событие изменения размера с помощью функции addEventListener() в JavaScript
  2. Добавить событие изменения размера с помощью функции onresize() в JavaScript

В этом руководстве будет обсуждаться добавление события изменения размера с помощью функций addEventListener() и onresize() в JavaScript.

Добавить событие изменения размера с помощью функции addEventListener() в JavaScript

Чтобы добавить событие изменения размера в окно, мы можем использовать функцию addEventListener() в JavaScript. Эта функция добавляет к объекту событие, содержащее функцию. Например, давайте добавим событие в окно объекта, чтобы получить его ширину и высоту и отобразить его на веб-странице. См. Код ниже.

 html> head>  title>title>  head> body>  span>Width = span>span id="SpanID1">span>  br />  span>Height = span>span id="SpanID2">span>  script type="text/javascript"> start(); window.addEventListener('resize', start);  function start()  document.getElementById('SpanID1').innerText = document.documentElement.clientWidth;  document.getElementById('SpanID2').innerText = document.documentElement.clientHeight; >  script>  body>  html> 

В приведенном выше коде мы добавили диапазон с текстом Width= , а после этого мы добавили пустой диапазон с идентификатором SpanID1 в раздел body. Мы добавили тег br для перемещения курсора на новую строку, а в новой строке мы добавили еще один диапазон с текстом Height= , а после этого мы добавили еще один пустой диапазон с идентификатором SpanID2 .

Идентификатор диапазона будет использоваться для получения элемента в JavaScript. В теге скрипта у нас есть функция start() , которая используется для изменения текста двух промежутков в зависимости от ширины и высоты окна. После функции start() мы добавили событие изменения размера, которое будет вызывать функцию start() , когда пользователь изменяет размер окна. Ширина и высота окна будут отображаться на странице и будут меняться по мере изменения размера окна. Вы можете сохранить приведенный выше код в HTML-файл, открыть его в любом браузере и изменить его размер, чтобы увидеть, работает ли код или нет. Вы также можете использовать функцию addEventListener() , чтобы добавить событие к любому объекту, например, к флажку.

Добавить событие изменения размера с помощью функции onresize() в JavaScript

Чтобы добавить событие изменения размера в окно, мы можем использовать функцию onresize() в JavaScript. Эта функция используется, чтобы указать, что произойдет, если размер окна изменится. Например, давайте добавим событие в окно объекта, чтобы получить его ширину и высоту и отобразить его на веб-странице. См. Код ниже.

 html> head>  title>title>  head> body>  span>Width = span>span id="SpanID1">span>  br />  span>Height = span>span id="SpanID2">span>  script type="text/javascript"> start(); window.onresize = start; function start()  document.getElementById('SpanID1').innerText = document.documentElement.clientWidth;  document.getElementById('SpanID2').innerText = document.documentElement.clientHeight; >  script>  body>  html> 

В приведенном выше коде функция start() будет вызываться при изменении размера окна. Как видите, результат такой же, как и у описанного выше метода.

Hello! I am Ammar Ali, a programmer here to learn from experience, people, and docs, and create interesting and useful programming content. I mostly create content about Python, Matlab, and Microcontrollers like Arduino and PIC.

Сопутствующая статья — JavaScript Event

Источник

Window: innerHeight property

The read-only innerHeight property of the Window interface returns the interior height of the window in pixels, including the height of the horizontal scroll bar, if present.

The value of innerHeight is taken from the height of the window’s layout viewport. The width can be obtained using the innerWidth property.

Value

An integer value indicating the window’s layout viewport height in pixels. The property is read only and has no default value.

To change the width of the window, call one of its resize methods, such as resizeTo() or resizeBy() .

Usage notes

To obtain the height of the window minus its horizontal scroll bar and any borders, use the root element’s clientHeight property instead.

Both innerHeight and innerWidth are available on any window or any object that behaves like a window, such as a tab or frame.

Examples

Assuming a frameset

.log(window.innerHeight); // or console.log(self.innerHeight); // will log the height of the frame viewport within the frameset console.log(parent.innerHeight); // will log the height of the viewport of the closest frameset console.log(top.innerHeight); // will log the height of the viewport of the outermost frameset 

To change the size of a window, see window.resizeBy() and window.resizeTo() .

To get the outer height of a window, i.e. the height of the whole browser window, see window.outerHeight .

Graphical example

The following figure shows the difference between outerHeight and innerHeight .

innerHeight vs. outerHeight illustration

Demo

HTML

p>Resize the browser window to fire the code>resizecode> event.p> p>Window height: span id="height">span>p> p>Window width: span id="width">span>p> 

JavaScript

const heightOutput = document.querySelector("#height"); const widthOutput = document.querySelector("#width"); function updateSize()  heightOutput.textContent = window.innerHeight; widthOutput.textContent = window.innerWidth; > updateSize(); window.addEventListener("resize", updateSize); 

Result

Specifications

Источник

JavaScript Window resize Event

The “resize” event in JavaScript is a built-in event triggered when the user changes the size of a browser window. This event can be used to adjust the layout or behavior of a web page in response to the new window size. The event is triggered/fired on the window object that denotes the browser window.

This post will illustrate the Window resize event in JavaScript.

What is the Window “resize” Event in JavaScript?

In JavaScript, the “resize” event is fired when the browser window size changes. You can attach a function to the resize event using the “addEventListener()” method on the window object. This event will trigger whenever the browser window is resized.

The following syntax is used for the resize event for resizing the window with the “addEventListener()” method:

It is recommended to remove the event listener to avoid any memory leaks. For removing the event listener, use the “removeEventListener()” method:

In the provided example, the length and the width of the window will display on the page while resizing the window.

First, create a span area for displaying the length and width of the window:

Then, in tag, define a function “windowResize()” where get the reference of the length and width elements to print the values:

function windowResize ( ) {
document.getElementById ( ‘height’ ) .innerText=document.documentElement.clientHeight;
document.getElementById ( ‘width’ ) .innerText = document.documentElement.clientWidth;
}

Call the “resize” event in the “addEventListener()” method and attach the defined function with the event:

Call the “windowResize()” for the first time:

The output indicates that the value is continuously changed while changing the window size:

That’s all about the window resize event in JavaScript.

Conclusion

The “resize” event in JavaScript is triggered when the size of a window or an element is changed. It can detect changes to the browser window’s size or a specific element. The event can be added to a window or element using the “addEventListener()” method and specifying “resize” as the event type. In this post, we illustrated the Window resize event in JavaScript.

About the author

Farah Batool

I completed my master’s degree in computer science. I am an academic researcher and love to learn and write about new technologies. I am passionate about writing and sharing my experience with the world.

Источник

Читайте также:  Python module attributes list
Оцените статью