recursal/MDN huggingface dataset:
Window: load event
==================

 The **`load`** event is fired when the whole page has loaded, including all dependent resources such as stylesheets, scripts, iframes, and images.
 This is in contrast to `DOMContentLoaded`, which is fired as soon as the page DOM has been loaded, without waiting for resources to finish loading.

This event is not cancelable and does not bubble.

**Note:** *All events named `load` will not propagate to `Window`*, even with `bubbles` initialized to `true`. To catch `load` events on the `window`, that `load` event must be dispatched directly to the `window`.

**Note:** The `load` event that is dispatched when the main document has loaded *is* dispatched on the `window`, but has two mutated properties: `target` is `document`, and `path` is `undefined`. These two properties are mutated due to legacy conformance.

Syntax
------

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


```js
addEventListener("load", (event) => {});

onload = (event) => {};
```

Event type
----------

A generic `Event`.

Examples
--------

Log a message when the page is fully loaded:


```js
window.addEventListener("load", (event) => {
  console.log("page is fully loaded");
});
```


The same, but using the `onload` event handler property:


```js
window.onload = (event) => {
  console.log("page is fully loaded");
};
```

### Live example

#### HTML


```html
<div class="controls">
  <button id="reload" type="button">Reload</button>
</div>

<div class="event-log">
  <label for="eventLog">Event log:</label>
  <textarea
 readonly
 class="event-log-contents"
 rows="8"
 cols="30"
 id="eventLog"></textarea>
</div>
```


```
body {
  display: grid;
  grid-template-areas: "control log";
}

.controls {
  grid-area: control;
  display: flex;
  align-items: center;
  justify-content: center;
}

.event-log {
  grid-area: log;
}

.event-log-contents {
  resize: none;
}

label,
button {
  display: block;
}

#reload {
  height: 2rem;
}
```


#### JavaScript


```js
const log = document.querySelector(".event-log-contents");
const reload = document.querySelector("#reload");

reload.addEventListener("click", () => {
  log.textContent = "";
  setTimeout(() => {
    window.location.reload(true);
  }, 200);
});

window.addEventListener("load", (event) => {
  log.textContent += "load\n";
});

document.addEventListener("readystatechange", (event) => {
  log.textContent += `readystate: ${document.readyState}\n`;
});

document.addEventListener("DOMContentLoaded", (event) => {
  log.textContent += `DOMContentLoaded\n`;
});
```


#### Result

Specifications
--------------

| Specification |
| --- |
| UI Events # event-type-load |
| HTML Standard # delay-the-load-event |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Document readyState API
* Related events:
    + `DOMContentLoaded`
    + `readystatechange`
    + `beforeunload`
    + `unload`
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.


```js
addEventListener("resize", (event) => {});

onresize = (event) => {};
```

Event type
----------

A generic `Event`.

Examples
--------

### Window size logger

The following example reports the window size each time it is resized.

#### HTML


```html
<p>Resize the browser window to fire the <code>resize</code> event.</p>
<p>Window height: <span id="height"></span></p>
<p>Window width: <span id="width"></span></p>
```


#### JavaScript


```js
const heightOutput = document.querySelector("#height");
const widthOutput = document.querySelector("#width");

function reportWindowSize() {
  heightOutput.textContent = window.innerHeight;
  widthOutput.textContent = window.innerWidth;
}

window.onresize = reportWindowSize;
```


#### Result

**Note:** The example output here is in an `<iframe>`, so the reported width and height values are for the `<iframe>`, not the window that this page is in. In particular, it will be hard to adjust the window size so as to see a difference in the reported height.

The effect is easier to see if you view the example in its own window.

### addEventListener equivalent

You could set up the event handler using the `addEventListener()` method:


```js
window.addEventListener("resize", reportWindowSize);
```

Specifications
--------------

| Specification |
| --- |
| CSSOM View Module # eventdef-window-resize |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.
Window: getSelection() method
=============================

 The **`Window.getSelection()`** method returns a
 `Selection` object representing the range of text selected by the user or
 the current position of the caret.

Syntax
------


```js
getSelection()
```

### Parameters

None.

### Return value

A `Selection` object.

 When cast to string, either by appending an empty string (`""`) or using
 `Selection.toString()`, this object returns the text selected.

 When called on an `<iframe>` that is not displayed (e.g., where
 `display: none` is set) Firefox will return `null`, whereas other
 browsers will return a `Selection` object with
 `Selection.type` set to `None`.

Examples
--------


```js
function foo() {
  const selObj = window.getSelection();
  alert(selObj);
  const selRange = selObj.getRangeAt(0);
  // do stuff with the range
}
```

Notes
-----

### String representation of the Selection object

 In JavaScript, when an object is passed to a function expecting a string (like `window.alert()` or `document.write()`), the object's
 `toString()` method is called and the returned value is
 passed to the function. This can make the object appear to be a string when used with
 other functions when it is really an object with properties and methods.

 In the above example, `selObj.toString()` is automatically called when it is
 passed to `window.alert()`. However, attempting to use a JavaScript String property
 or method such as
 `length`
 or
 `substr`
 directly on a `Selection` object will result in an error if it does not
 have that property or method and may return unexpected results if it does. To use a
 `Selection` object as a string, call its `toString()` method
 directly:


```js
const selectedText = selObj.toString();
```


* `selObj` is a `Selection` object.
* `selectedText` is a string (Selected text).
### Related objects

 You can call `Document.getSelection()`, which works identically to
 `Window.getSelection()`.

 It is worth noting that currently `getSelection()` doesn't work on the
 content of `<textarea>` and `<input>` elements in Firefox
 and Edge (Legacy). `HTMLInputElement.setSelectionRange()`
 or the `selectionStart` and `selectionEnd` properties could be
 used to work around this.

 Notice also the difference between *selection* and *focus*.
 `Document.activeElement` returns the focused element.

Specifications
--------------

| Specification |
| --- |
| Selection API # dom-window-getselection |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Selection API
* `Selection`
* `Range`
* `Document.getSelection()`
* `HTMLInputElement.setSelectionRange()`
Window: cookieStore property
============================

**Secure context:** This feature is available only in secure contexts (HTTPS), in some or all supporting browsers.

**Experimental:** **This is an experimental technology**  
Check the Browser compatibility table carefully before using this in production.

The **`cookieStore`** read-only property of the `Window` interface returns a reference to the `CookieStore` object for the current document context. This is an entry point for the Cookie Store API.

Value
-----

A `CookieStore` object instance.

Specifications
--------------

| Specification |
| --- |
| Cookie Store API # dom-window-cookiestore |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.
Window: alert() method
======================

`window.alert()` instructs the browser to display a dialog with an optional message, and to wait until the user dismisses the dialog.

Under some conditions — for example, when the user switches tabs — the browser may not actually display a dialog, or may not wait for the user to dismiss the dialog.

Syntax
------


```js
alert()
alert(message)
```

### Parameters

`message` Optional

 A string you want to display in the alert dialog, or, alternatively, an object that
 is converted into a string and displayed.


### Return value

None (`undefined`).

Examples
--------


```js
window.alert("Hello world!");
alert("Hello world!");
```


Both produce:

![Black alert dialog box. At the top left small circle icon follow by white open and close square brackets containing this white text: JavaScript application. Below on the left, a Hello world! white text. And on the bottom right a small blue button. The button's text is: ok in black.](/en-US/docs/Web/API/Window/alert/alerthelloworld.png)

Notes
-----

 The alert dialog should be used for messages which do not require any response on the
 part of the user, other than the acknowledgement of the message.

 Dialog boxes are modal windows - they
 prevent the user from accessing the rest of the program's interface until the dialog box
 is closed. For this reason, you should not overuse any function that creates a dialog
 box (or modal window).

Alternatively `<dialog>` element can be used to display alerts.

Specifications
--------------

| Specification |
| --- |
| HTML Standard # dom-alert-dev |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `<dialog>` element
* `confirm`
* `prompt`
Window: statusbar property
==========================

Returns the `statusbar` object.

This is one of a group of `Window` properties that contain a boolean `visible` property, that used to represent whether or not a particular part of a web browser's user interface was visible.

For privacy and interoperability reasons, the value of the `visible` property is now `false` if this `Window` is a popup, and `true` otherwise.

Value
-----

An object containing a single property:

`visible` Read only 

A boolean property, `false` if this `Window` is a popup, and `true` otherwise.

Specifications
--------------

| Specification |
| --- |
| HTML Standard # dom-window-statusbar-dev |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `window.locationbar`
* `window.menubar`
* `window.personalbar`
* `window.scrollbars`
* `window.toolbar`
Window: close() method
======================

 The **`Window.close()`** method closes the current window, or
 the window on which it was called.

 This method can only be called on windows that were opened by a script using the
 `Window.open()` method, or on top-level windows that have a single history entry. If the window doesn't match these requirements, an error
 similar to this one appears in the console:
 `Scripts may not close windows that were not opened by script.`

 Note also that `close()` has no effect when called on `Window`
 objects returned by
 `HTMLIFrameElement.contentWindow`.

Syntax
------


```js
close()
```

### Parameters

None.

### Return value

None (`undefined`).

Examples
--------

### Closing a window opened with `window.open()`

 This example shows a method which opens a window and a second one which closes the
 window; this demonstrates how to use `Window.close()` to close a window
 opened by calling `window.open()`.


```js
//Global variable to store a reference to the opened window
let openedWindow;

function openWindow() {
  openedWindow = window.open("moreinfo.htm");
}

function closeOpenedWindow() {
  openedWindow.close();
}
```

Specifications
--------------

| Specification |
| --- |
| HTML Standard # dom-window-close-dev |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.
Window: screenY property
========================

The **`Window.screenY`** read-only property returns the vertical distance, in CSS pixels, of the top border of the user's browser viewport to the top edge of the screen.

**Note:** An alias of `screenY` was implemented across modern browsers in more recent times — `Window.screenTop`. This was originally supported only in IE but was introduced everywhere due to popularity.

Value
-----

A number equal to the number of CSS pixels from the top edge of the browser viewport to the top edge of the screen.

Examples
--------

In our screenleft-screentop example, you'll see a canvas onto which has been drawn a circle. In this example we are using `Window.screenLeft`/`Window.screenTop` plus `Window.requestAnimationFrame()` to constantly redraw the circle in the same physical position on the screen, even if the window position is moved.


```js
initialLeft = window.screenLeft + canvasElem.offsetLeft;
initialTop = window.screenTop + canvasElem.offsetTop;

function positionElem() {
  let newLeft = window.screenLeft + canvasElem.offsetLeft;
  let newTop = window.screenTop + canvasElem.offsetTop;

  let leftUpdate = initialLeft - newLeft;
  let topUpdate = initialTop - newTop;

  ctx.fillStyle = "rgb(0 0 0)";
  ctx.fillRect(0, 0, width, height);
  ctx.fillStyle = "rgb(0 0 255)";
  ctx.beginPath();
  ctx.arc(
    leftUpdate + width / 2,
    topUpdate + height / 2 + 35,
    50,
    degToRad(0),
    degToRad(360),
    false,
  );
  ctx.fill();

  pElem.textContent = `Window.screenLeft: ${window.screenLeft}, Window.screenTop: ${window.screenTop}`;

  window.requestAnimationFrame(positionElem);
}

window.requestAnimationFrame(positionElem);
```


These work in exactly the same way as `screenX`/`screenY`.

Also in the code we include a snippet that detects whether `screenLeft` is supported, and if not, polyfills in `screenLeft`/`screenTop` using `screenX`/`screenY`.


```js
if (!window.screenLeft) {
  window.screenLeft = window.screenX;
  window.screenTop = window.screenY;
}
```

Specifications
--------------

| Specification |
| --- |
| CSSOM View Module # dom-window-screeny |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `window.screenTop`
* `window.screenX`
Window: document property
=========================

**`window.document`** returns a reference to the document contained in the window.

Value
-----

A document object.

Examples
--------


```js
console.log(window.document.title);
```

Specifications
--------------

| Specification |
| --- |
| HTML Standard # dom-document-dev |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.
Window: afterprint event
========================

The **`afterprint`** event is fired after the associated document has started printing or the print preview has been closed.

The `beforeprint` and `afterprint` events allow pages to change their content before printing starts (perhaps to remove a banner, for example) and then revert those changes after printing has completed. In general, you should prefer the use of a `@media print` CSS at-rule, but it may be necessary to use these events in some cases.

Syntax
------

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


```js
addEventListener("afterprint", (event) => {});
onafterprint = (event) => {};
```

Event type
----------

A generic `Event`.

Examples
--------

Using `addEventListener()`:


```js
window.addEventListener("afterprint", (event) => {
  console.log("After print");
});
```


Using the `onafterprint` event handler property:


```js
window.onafterprint = (event) => {
  console.log("After print");
};
```

Specifications
--------------

| Specification |
| --- |
| HTML Standard # event-afterprint |
| HTML Standard # handler-window-onafterprint |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Related events: `beforeprint`
Window: setImmediate() method
=============================

**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

**Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

This method is used to break up long running operations and run a callback function immediately after the browser has completed other operations such as events and display updates.

Syntax
------


```js
setImmediate(func)
setImmediate(func, param1)
setImmediate(func, param1, param2)
setImmediate(func, param1, param2, /\* …, \*/ paramN)
```

### Parameters

`func`

The function you wish to call.

`param1`, …, `paramN`

All parameters will be passed directly to your function.

### Return value

The ID of the immediate which can be used later with `window.clearImmediate`.

Notes
-----

The `clearImmediate` method can be used to clear the immediate actions, just like `clearTimeout` for `setTimeout()`.

This method can be used instead of the `setTimeout(fn, 0)` method to execute heavy operations.

The feature can be emulated in a few different ways:

* `postMessage` can be used to trigger an immediate but yielding callback.
* `MessageChannel` can be used reliably inside of Web Workers whereas the
 semantics of postMessage mean it cannot be used there.
* `setTimeout(fn, 0)` *can* potentially be used, however as it is clamped to 4ms for timers nested more than 5 levels deep per the HTML spec, it does not make for a suitable polyfill for the natural immediacy of `setImmediate`.

All of these techniques are incorporated into a robust setImmediate polyfill.

Specifications
--------------

 Not part of any current specifications.
 The Efficient Script Yielding specification is no longer being worked on.

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Polyfill of `setImmediate` in `core-js`
* Microsoft `setImmediate` API Demo
* `Window.clearImmediate()`
* `Window.requestIdleCallback()`
Window: clearImmediate() method
===============================

**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

**Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

This method clears the action specified by `window.setImmediate`.

Syntax
------


```js
clearImmediate(immediateID)
```

### Parameters

`immediateID`

The ID returned by `window.setImmediate`.

### Return value

None (`undefined`).

Examples
--------


```js
let immediateID = setImmediate(() => {
  // Run some code
});

document.getElementById("button").addEventListener(() => {
  clearImmediate(immediateID);
});
```

Specifications
--------------

 Not part of any current specifications.
 The Efficient Script Yielding
 specification is no longer being worked on.

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Polyfill of `clearImmediate` in `core-js`
* `Window.setImmediate()`
Window: scrollTo() method
=========================

**`Window.scrollTo()`** scrolls to a particular set of
 coordinates in the document.

Syntax
------


```js
scrollTo(x-coord, y-coord)
scrollTo(options)
```

### Parameters

* `x-coord` is the pixel along the horizontal axis of the
 document that you want displayed in the upper left.
* `y-coord` is the pixel along the vertical axis of the document
 that you want displayed in the upper left.

- or -

`options`

A dictionary containing the following parameters:

`top`

Specifies the number of pixels along the Y axis to scroll the window or element.

`left`

Specifies the number of pixels along the X axis to scroll the window or element.

`behavior`

Determines whether scrolling is instant or animates smoothly. This option is a string which must take one of the following values:

* `smooth`: scrolling should animate smoothly
* `instant`: scrolling should happen instantly in a single jump
* `auto`: scroll behavior is determined by the computed value of `scroll-behavior`


### Return value

None (`undefined`).

Examples
--------


```js
window.scrollTo(0, 1000);
```


Using `options`:


```js
window.scrollTo({
  top: 100,
  left: 100,
  behavior: "smooth",
});
```

Notes
-----

`Window.scroll()` is effectively the same as this method. For relative
 scrolling, see `Window.scrollBy()`, `Window.scrollByLines()`,
 and `Window.scrollByPages()`.

 For scrolling elements, see `Element.scrollTop` and
 `Element.scrollLeft`.

Specifications
--------------

| Specification |
| --- |
| CSSOM View Module # dom-window-scrollto |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.