Window resize with javascript

JavaScript Window

Summary: in this tutorial, you will learn about the JavaScript window object which is the global object of JavaScript in the browser and exposes the browser’s functionality.

The window object is global

The global object of JavaScript in the web browser is the window object. It means that all variables and functions declared globally with the var keyword become the properties and methods of the window object. For example:

var counter = 1; var showCounter = () => console.log(counter); console.log(window.counter); window.showCounter(); Code language: JavaScript (javascript)

Because the counter variable and the showCounter() function are declared globally with the var keyword, they are automatically added to the window object.

If you don’t want to pollute the window object, you can use the let keyword to declare variables and functions.

The window object exposes the browser’s functionality

The window object exposes the functionality of the web browser to the webpage.

1) Window size

The window object has four properties related to the size of the window:

  • The innerWidth and innerHeight properties return the size of the page viewport inside the browser window (not including the borders and toolbars).
  • The outerWidth and outerHeight properties return the size of the browser window itself.
Читайте также:  Add certificate https java

Also, document.documentElement.clientWidth and document.documentElement.clientHeight properties indicate the width and height of the page viewport.

To get the size of the window, you use the following snippet:

const width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth; const height = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight; Code language: JavaScript (javascript)

2) Open a new window

To open a new window or tab, you use the window.open() method:

window.open(url, windowName, [windowFeatures]); Code language: CSS (css)

The window.open() method accepts three arguments: the URL to load, the window target and a string of window features.

The third argument is a command-delimited string of settings specifying displaying information for the new window such as width, height, menubar, and resizable.

The window.open() method returns a WindowProxy object, which is a thin wrapper of the window object. In case the new window cannot be opened, it returns null .

For example, to open a new window that loads the page about.html at localhost, you use the following code:

let url = 'http://localhost/js/about.html'; let jsWindow = window.open(url,'about');Code language: JavaScript (javascript)

The code opens the page about.html in a new tab. If you specify the height and width of the window, it will open the URL in a new separated window instead of a new tab:

let features = 'height=600,width=800', url = 'http://localhost/js/about.html'; let jsWindow = window.open(url, 'about', features);Code language: JavaScript (javascript)

To load another URL on an existing window, you pass an existing window name to the window.open() method. The following example loads the contact.html webpage to the contact window:

window.open('http://localhost/js/contact.html','about');Code language: JavaScript (javascript)

Put it all together. The following code opens a new window that loads the webpage about.html and then after 3 seconds, it loads the webpage contact.html in the same window:

let features = 'height=600,width=800', url = 'http://localhost/js/about.html'; let jsWindow = window.open(url, 'about', features); setTimeout(() => < window.open('http://localhost/js/contact.html', 'about') >, 3000);Code language: JavaScript (javascript)

3) Resize a window

To resize a window you use the resizeTo() method of the window object:

window.resizeTo(width,height);Code language: JavaScript (javascript)

The following example opens a new window that loads the http://localhost/js/about.html page and resize it to (600,300) after 3 seconds:

let jsWindow = window.open( 'http://localhost/js/about.html', 'about', 'height=600,width=800'); setTimeout(() => < jsWindow.resizeTo(600, 300); >, 3000);Code language: JavaScript (javascript)

The window.resizeBy() method allows you to resize the current window by a specified amount:

window.resizeBy(deltaX,deltaY);Code language: JavaScript (javascript)
let jsWindow = window.open( 'http://localhost/js/about.html', 'about', 'height=600,width=600'); // shrink the window, or resize the window // to 500x500 setTimeout(() => < jsWindow.resizeBy(-100, -100); >, 3000);Code language: JavaScript (javascript)

4) Move a window

To move a window to a specified coordinate, you use the moveTo() method:

window.moveTo(x, y);Code language: JavaScript (javascript)

In this method, x and y are horizontal and vertical coordinates to be moved to. The following example opens a new window and moves it to (0,0) coordinate after 3 seconds:

let jsWindow = window.open( 'http://localhost/js/about.html', 'about', 'height=600,width=600'); setTimeout(() => < jsWindow.moveTo(500, 500); >, 3000);Code language: JavaScript (javascript)

Similarly, you can move the current window by a specified amount:

let jsWindow = window.open( 'http://localhost/js/about.html', 'about', 'height=600,width=600'); setTimeout(() => < jsWindow.moveBy(100, -100); >, 3000);Code language: JavaScript (javascript)

5) Close a window

To close a window, you use the window.open() method:

window.open()Code language: JavaScript (javascript)

The following example opens a new window and closes it after 3 seconds:

let jsWindow = window.open( 'http://localhost/js/about.html', 'about', 'height=600,width=600'); setTimeout(() => < jsWindow.close(); >, 3000); Code language: JavaScript (javascript)

6) The window.opener property

A newly created window can reference back to the window that opened it via the window.opener property. This allows you to exchange data between the two windows.

Summary

  • The window is the global object in the web browser.
  • The window object exposes the functionality of the web browser.
  • The window object provides methods for manipulating a window such as open() , resize() , resizeBy() , moveTo() , moveBy() , and close() .

Источник

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 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.

Источник

Оцените статью