W02 Learning Activity: The Window Interface
Overview
You have already used the window
object many times when working with JavaScript. For example, you
have manipulated the DOM and it was this the global window
object that provided the access. You have
also used the
window.localStorage
to store basic data in the browser.
You may have noted that the window
syntax is often omitted because it is the global object in the
browser environment and therefore, not required.
window.document.querySelector(".message")
// can be written as:
document.querySelector(".message")
// and
window.localStorage.setItem("key", "value")
// can be written as:
localStorage.setItem("key", "value")
Prepare
The Window interface defines the properties and methods available to the global
object like the .location
, .localStorage
, and alert()
. It is the
top-level object in the JavaScript hierarchy, the parent of all other objects in the browser.
It provides access to the browser's features and functionality including methods for manipulating the browser
window and access to window properties. Each tab in the browser is represented its
own window
object. However, some properties and methods apply to the containing browser window.
For example, the window.innerWidth
and window.innerHeight
properties return the width
and height of the browser window's viewport.
Enter these two lines of code in your browser's DevTools console panel.
window.innerWidth
window.innerHeight
What values are returned to the console? How might these values be useful in responsive design?
What happens when you enter
window.open("https://pathway.edu")
in the console?
Activity Instructions
A commonly used example of the Window interface is detecting when the user resizes the browser window. This is useful for responsive behavior or adjusting elements dynamically. In this activity, you will look at an example and modify that example to use additional features:
Review CodePen Example
- Open this CodePen Responsive Navigation
- Review the interaction when you resize the displayed page manually.
This example removes the responsive class when the window is manually resized by the user.Look for the
window.addEventListener('resize')
function in the JavaScript panel.
Display Window Properties
- Fork the CodePen from the previous step.
- Using
window.innerWidth
andwindow.innerHeight
, display a message in the<aside>
element provided that displays the currentinnerWidth
andinnerHeight
.
Optional Resources
- The Window Interface – MDN — This page provides a detailed overview of the Window interface and its properties and methods.
- The Window Object – W3Schools