- Отслеживаем «onresize» на элементе
- Тест-Код:
- Код:
- Window: resize event
- Syntax
- Event type
- Event properties
- Examples
- Window size logger
- HTML
- JavaScript
- Result
- addEventListener equivalent
- Specifications
- Browser compatibility
- Found a content problem with this page?
- MDN
- Support
- Our communities
- Developers
- onresize Event
- Browser Support
- Syntax
- Technical Details
- More Examples
- Example
- COLOR PICKER
- Report Error
- Thank You For Helping Us!
- JavaScript onresize
- How onresize Event works in JavaScript?
- Examples of JavaScript onresize
- Example #1
- Conclusion
- Recommended Articles
Отслеживаем «onresize» на элементе
Достаточно древняя задача отслеживания события изменения размеров произвольного элемента на странице. Актуально при создании модульно-независимой структуры для корректировки размеров и иных сss-атрибутов нужного элемента на странице, в частности блоков с периодической Аякс-подгрузкой (например: новостных). Типично решается через таймирование и периодический опрос размеров элемента. Новый вариант, — не использующий таймирующий опрос.
Трюк: Внутрь элемента вставляем пустой фрейм с position:absolute и 100%- (ыми) размерами, придаём элементу position:relative; . И отслеживаем frame.onresize :
Тест-Код:
Тут контент .
Под спойлером
Код:
Тут контент .
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.
onresize Event
The onresize event occurs when the browser window has been resized.
Tip: To get the size of an element, use the clientWidth, clientHeight, innerWidth, innerHeight, outerWidth, outerHeight, offsetWidth and/or offsetHeight properties.
Browser Support
Syntax
In JavaScript, using the addEventListener() method:
Technical Details
Bubbles: | No |
---|---|
Cancelable: | No |
Event type: | UiEvent if generated from a user interface, Event otherwise |
HTML tags: | |
DOM Version: | Level 2 Events |
More Examples
Example
Using the addEventListener() method to attach the «resize» event on the window object.
COLOR PICKER
Report Error
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
Thank You For Helping Us!
Your message has been sent to W3Schools.
Top Tutorials
Top References
Top Examples
Get Certified
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.
JavaScript onresize
The JavaScript onresize function is a property that can be used in event handling. It triggers whenever there is an event of resizing takes place. This event happens when the window of a particular page is resized. It is used to resize to different sizes. It can also be used with different internet browsers and used as per necessity. It is a part of the Document Object Model (DOM) and can be used very easily.
Web development, programming languages, Software testing & others
The JavaScript onresize function can be used as below:
window.onresize = functionName;
The functionName is a function name or a function expression which will be receiving the FocusEvent object as its only argument. This function will be responsible for handling the argument sent by the FocusEvent object and take care of it.
We will also need the addEventListener() method which can be used as below:
object.addEventListener("resize", myCode);
We use the above syntax for listening to the events.
How onresize Event works in JavaScript?
The working of the onresize function is very easy.
This example helps in resizing an existing window and also keeps a count of it.
Let us resize the browser window.
Window has been 0 times.
document.getElementsByTagName("BODY")[0].onresize = function() ; var x = 0; function myResizeFunction()
Here in the body we are printing the count of how many times the window is resized. The script that follows contains the onresize function. This function is calling the myResizeFunction(). We have then declared a variable x which will keep a count of the resizing. As mentioned above the onresize function takes the user defined function as a parameter and then performs its function. Here, in this function whenever the window is resized the count is incremented. It signifies that this function is calling onresize whenever the window is being resized. In addition to this we have some more functions for resizing.
When the first time program is run, then above output will be displayed. But when the window is resized then the counter will increase. To check it you can just minimize your browser window, the Event will be captured and the count will increase. Below is the output after resizing the page.
Examples of JavaScript onresize
Given below are the examples of JavaScript onresize:
Example #1
Let us see an example of resizing windows with using an . Since the code will be running on an there will be needed a setup that can help in actually seeing the resizing effect.
Changing thesize of the browser window to check the working of onresize event.
Window height:
Window width:
In this program we have used two variables for accepting the height and width of the window. We make use of querySelector which helps us to store the height and width. The function letsresize() is making use of different functions.
These functions are as below:
- clientWidth, clientHeight
- innerWidth, innerHeight
- outerWidth, outerHeight
- offsetWidth, offsetHeight
These functions can help us in setting the height and width of window, client or the server. We have used one of these functions in order to set the size of the text as per the window being resized. After this, we are using the onresize function where we are calling the letsresize function. Below will be the output of the above code. As mentioned earlier you will have to set the prior to running this program.