Categories
JavaScript

Introducing the JavaScript Window Object — URL and activeElement

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 explore the URL , activeElement and the fullscreenElement properties.

window.document.URL

We can use the URL property to get the URL of the currently loaded page as a string. It is a read-only property. For example, we can write:

console.log(window.document.URL);

Then we should get something like https://fiddle.jshell.net/_display/.

window.document.activeElement

The activeElement property is a read only property that returns the Element object which is in focus. The activeElement often will return an input or a textarea object if it has text selection at the time. If this is the case, we can get more details with the selectionStart and selectionEnd properties. Focused elements may also be a select element or an input element of the type button , checkbox or radio . Users can press the tab key to move the focus on a different element that they’re currently focused in. A space bar can activate an input element if it involves selection like a checkbox or a radio button. For macOS systems, elements that aren’t inputs aren’t focusable by default. For example, if we have the following HTML markup:

<form>
  <textarea name="textarea-1" id="textarea-1" rows="7" cols="40">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi interdum justo vel nulla laoreet mollis. Curabitur eget turpis id mi venenatis efficitur vestibulum sit amet libero. Fusce non varius tellus. Vestibulum a nisi venenatis, accumsan diam eget, aliquet ex. Sed tristique purus at est pulvinar, eu tincidunt justo vestibulum. Mauris fringilla interdum ipsum sed blandit. Suspendisse sollicitudin ut mi eget tincidunt. Sed et dolor diam. Praesent venenatis ipsum a libero interdum, in sagittis tellus elementum. Pellentesque in est vitae dui efficitur lacinia eget porta diam.

  </textarea>

  <textarea name="textarea-2" id="textarea-2" rows="7" cols="40">Duis urna dolor, fringilla quis dui quis, bibendum ornare ligula. Fusce ut nisi eu orci elementum rhoncus. Morbi ut tortor mauris. Morbi pretium tempus erat vitae dignissim. Duis et dolor vel metus tempor laoreet nec eget est. Curabitur tincidunt ullamcorper ante, sit amet iaculis arcu condimentum vitae. Donec tincidunt convallis maximus. Mauris pulvinar sem velit, congue volutpat nisl commodo sit amet. Duis ac est eu orci venenatis lacinia.

  </textarea>
</form>

and the following JavaScript code:

const textarea1 = document.getElementById('textarea-1');
const textarea2 = document.getElementById('textarea-2');
const onMouseUp = () => {
  console.log(document.activeElement);
}
textarea1.addEventListener('mouseup', onMouseUp, false);
textarea2.addEventListener('mouseup', onMouseUp, false);

Then when we click either of the 2 textarea elements, then we see the activeElement being the textarea element that’s currently in focus. That is, the one that the cursor is currently in after it was clicked. Since the activeElement is an Element object, we can log its properties. We can change the code to the following to get the id and the value for the currently focused textarea element:

const textarea1 = document.getElementById('textarea-1');
const textarea2 = document.getElementById('textarea-2');
const onMouseUp = () => {
  const {
    id,
    value
  } = document.activeElement
  console.log(id);
  console.log(value);
}
textarea1.addEventListener('mouseup', onMouseUp, false);
textarea2.addEventListener('mouseup', onMouseUp, false);

Then we get:

textarea-1

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi interdum justo vel nulla laoreet mollis. Curabitur eget turpis id mi venenatis efficitur vestibulum sit amet libero. Fusce non varius tellus. Vestibulum a nisi venenatis, accumsan diam eget, aliquet ex. Sed tristique purus at est pulvinar, eu tincidunt justo vestibulum. Mauris fringilla interdum ipsum sed blandit. Suspendisse sollicitudin ut mi eget tincidunt. Sed et dolor diam. Praesent venenatis ipsum a libero interdum, in sagittis tellus elementum. Pellentesque in est vitae dui efficitur lacinia eget porta diam.

when we click on the first textarea and we get:

textarea-2

Duis urna dolor, fringilla quis dui quis, bibendum ornare ligula. Fusce ut nisi eu orci elementum rhoncus. Morbi ut tortor mauris. Morbi pretium tempus erat vitae dignissim. Duis et dolor vel metus tempor laoreet nec eget est. Curabitur tincidunt ullamcorper ante, sit amet iaculis arcu condimentum vitae. Donec tincidunt convallis maximus. Mauris pulvinar sem velit, congue volutpat nisl commodo sit amet. Duis ac est eu orci venenatis lacinia.

if we click on the second textarea . Likewise, we can do that with radio buttons. If we have the following HTML code:

<form>
  <input type='radio' id='choice1' name='choice'> Choice 1
  <input type='radio' id='choice2' name='choice'> Choice 2
</form>

and we modify the JavaScript code slightly like:

const choice1 = document.getElementById('choice1');
const choice2 = document.getElementById('choice2');
const onMouseUp = () => {
  const {
    id,
    value
  } = document.activeElement
  console.log(id);
  console.log(value);
}
choice1.addEventListener('mouseup', onMouseUp, false);
choice2.addEventListener('mouseup', onMouseUp, false);

Then we get the ID of the radio button that was clicked on and the value of the selected radio button, which should always be 'on' since it’s the chosen radio button. For checkboxes, we can write the following HTML code:

<form>
  <input type='checkbox' id='choice1' name='choice'> Choice 1
  <input type='checkbox' id='choice2' name='choice'> Choice 2
</form>

Then we write the following JavaScript:

const choice1 = document.getElementById('choice1');
const choice2 = document.getElementById('choice2');
const onClick = () => {
  const {
    id,
    checked
  } = document.activeElement
  console.log(id);
  console.log(checked);
}
choice1.addEventListener('click', onClick, false);
choice2.addEventListener('click', onClick, false);

In the code above, we switched to listening to the click event to get the right checked value of the currently focused activeElement . We switched from getting the value property to the checked property so that we get the right value for the checkbox.

window.document.fullscreenElement

The fullscreenElement is a read-only property that returns the Element object that’s currently being presented in full screen in the current document, or returns null if full-screen mode isn’t currently in use. It can be used to get the element that has some action done to it to make the browser go full screen. 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 then add the following JavaScript code to main.js :

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

Then when we click the img element in the HTML page the click event will be triggered, which then will run the click handler we passed into the img.addEventListener method as the second argument. The requestFullScreen which we called on the img object which is the DOM object for the img element we have in the HTML, will make the browser tab go full screen. This will resolve the promise and then the window.document.fullscreenElement will be logged by the console.log . It should log the img element which we clicked to make the browser go full screen since now the img element is presented in full-screen mode after it’s clicked. There’s no guarantee that the full-screen mode operation will succeed. If the permission to go full screen is denied then the promise returned by the requestFullScreen method will be rejected then a fullscreenerror event will be triggered.

The URL , activeElement and the fullscreenElement properties are very useful properties. The URL property lets us get the URL of the currently loaded page as a string. To get the currently focused element, we can use the activeElement property. We get the input, textarea or select elements that’s currently in focus. With the fullscreenElement we can get the DOM element that is shown in full-screen mode. That is the UI element that is being displayed when the browser is in full-screen mode. For example, if we click an image to make the browser go full screen then fullscreenElement is the image we click on since it’s now presented in full-screen mode.

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 *