Categories
JavaScript

Introducing the JavaScript Window Object — PointerLockElement and More

Spread the love

The window object is a global object that has the properties pertaining to the current DOM document, which is the things that are in the tab of a browser. The document property of the window object has the DOM document and associated nodes and methods that we can use to manipulate the DOM nodes and listen to events for each node. Since the window object is global, it’s available in every part of the application. When a variable is declared without the var , let or const keywords, they’re automatically attached to the window object, making them available to every part of your web app. This is only applicable when strict mode is disabled. If it’s enabled, then declaring variables without var , let , or const will be stopped an error since it’s not a good idea to let us declare global variables accidentally. The window object has many properties. They include constructors, value properties and methods. There’re methods to manipulate the current browser tab like opening and closing new popup windows, etc.

In a tabbed browser, each tab has its own window object, so the window object always represent the state of the currently opened tab in which the code is running. However, some properties still apply to all tabs of the browser like the resizeTo method and the innerHeight and innerWidth properties.

Note that we don’t need to reference the window object directly for invoking methods and object properties. For example, if we want to use the window.Image constructor, we can just write new Image() . In this article, we continue to look at what’s in the window object. In the previous sections, we looked at the constructors and some of the properties of the window object, including using the customElements to build a Web Component, and the crypto object to do cryptography on the client using symmetric and asymmetric encryption algorithms. In this article, we will look at the pointerLockElement property, the styleSheets property and the onfullscreenchange event handler.

window.document.pointerLockElement

The pointerLockElement property is a read-only property that provides the Element object that set as the target for mouse events when the pointer is locked. It’s null if the lock is pending, the pointer is unlocked, or the target is in another document. For example, if we have the following HTML:

<!DOCTYPE html>
<html>
  <head>
    <title>Full Screen</title>
  </head>
  <body>
    <img
      src="https://images.unsplash.com/photo-1537498425277-c283d32ef9db?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=757&q=80"
      id="img"
    />
    <script src="main.js"></script>
  </body>
</html>

and the following JavaScript code in main.js :

const img = document.getElementById("img");
img.addEventListener("click", async () => {
  await img.requestPointerLock();
});

document.addEventListener(
  "pointerlockchange",
  () => {
    console.log(window.document.pointerLockElement);
  },
  false
);

Then we can lock the mouse pointer to the element that called the requestPointerLock method and succeeded in securing the pointer lock. In the code above, we have an img element that we attached an click event listener by passing in an event handler function to let our code request the pointer lock by calling the requestPointerLock method. We called this method on the img element object. Once we clicked on the image. The pointer is locked to the img element, and the pointerlockchange will be triggered. Once that triggers the event handler function that we passed into the document.addEventListener is called, which will then log the window.document.pointerLockElement object, which will log the img object that secured the pointer lock and where the mouse pointer is locked in. There’s also a pointerlockerror event to handle the case when the pointer lock didn’t get secured successfully.

window.document.styleSheets

We can get all the style sheet link elements with the styleSheets property. It’s a read-only property that returns a StyleSheetList or CSSStyleSheet objects. These objects are array-like objects, so we can loop through them with a for loop or a for...of loop. However, array methods aren’t available for these objects. The list of style sheets in the StyleSheetList or CSSStyleSheet object returned are order in a specific way. The StyleSheet objects that are retrieved from the link headers are placed first sorted in the same order as in the head tag, then StyleSheet objects are retrieved from the DOM are placed after the ones in the head , and these ones are sorted in tree order. The DOM tree is traversed in a preorder, depth-first way, so the root will be traversed, then the browser will go through left most nodes and then go down the tree and move to the right afterward. For example, if we have the following code in the HTML file:

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

<link href="https://fonts.googleapis.com/css?family=Roboto&display=swap" rel="stylesheet">

Then we can loop through it in the JavaScript by getting the StyleSheet objects with the document.styleSheets property and the loop through it with the for...of like in the following code:

for (const sheet of document.styleSheets) {
  console.log(sheet);
}

Alternatively, we can use the for loop to do the same thing:

for (let i = 0; i < document.styleSheets.length; i++) {
  console.log(document.styleSheets[i]);
}

A StyleSheet object has the properties which reflect the attributes of the link tag and more. These are the properties of a StyleSheet object:

  • disabled — A boolean property that represents whether the current style sheet has been applied or not
  • href —A read-only string property that represents the location of the style sheet.
  • media — A read-only MediaList that represents the intended destination medium for style information
  • ownerNode — A read-only Node object that associates the style sheet with the current document
  • parentStyleSheet — A read-only property that returns the parent StyleSheet object including this one, if any and returns null if they don’t exist.
  • title — A read-only string property that represents the advisory title of the current style sheet.
  • type —A read only string property that represents the style sheet language for this style sheet.

window.document.onfullscreenchange

The onfullscreenchange property is an event handler that we can set to handle the fullscreenchange event. The fullscreenchange event is fired immediately when the document transitions in and out of full screen mode. The onfullscreenchange event handler will run when the fullscreenchange event is triggered. For example, if we have the following HTML code:

<!DOCTYPE html>
<html>
  <head>
    <title>Full Screen</title>
  </head>
  <body>
    <img
      src="https://images.unsplash.com/photo-1537498425277-c283d32ef9db?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=757&q=80"
      id="img"
    />
    <script src="main.js"></script>
  </body>
</html>

and the following JavaScript code in main.js :

const img = document.getElementById("img");
document.addEventListener("click", async () => {
  await img.requestFullscreen();
});

document.onfullscreenchange = event => {
  console.log("onfullscreenchange");
  console.log(window.document.fullscreenElement);
};

Then when we click on the web page, we will see the onfullscreenchange event handler being run since the fullscreenchange event has been triggered as we click the page to go full screen. Likewise, if we press the Esc key to close the full screen mode, the onfullscreenchange event handler function is run again since the fullscreenchange event is triggered again. In the example, we attached an event handler to the click event of the document object, which is the web page, by using the addEventListener method. Then we passed in the event handler function to the addEventListener method, which then runs the img.requestFullscreen() method to request full-screen mode when the web page is clicked. Once it succeeds, then the onfullscreenchange event handler function we assigned to it is called, and when we exited out of full-screen mode, it’s called again. To check if we’re in full-screen mode, we can use the window.document.fullscreenElement object. If we are in full screen, then there should be an object logged which is the HTML Element that we presented in full screen. If we exited out of full-screen mode, then window.document.fullscreenElement should be null .

The pointerLockElement property let us get the element that the cursor is in when pointer lock is activated. If we want to look at the style sheets in our JavaScript file, the styleSheets property will get us the style sheets in the form of JavaScript objects that we can enable and disable and also get the attributes and values we defined. The onfullscreenchange event handler let us handle the fullscreenchange event which is triggered when we go in and out of full-screen mode. We can check for full-screen mode with the window.document.fullscreenElement property, which should have an Element if we’re in full-screen mode and null otherwise.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *