Are you familiar with the window
object?
As a backend developer hacking together frontends, I copy/pasted functions containing the window
object (without understanding it) more than I’d like to admit.
But as I push myself further into frontend development, it’s become useful to actually understand it.
In a nutshell, the window
object,
- Represents the current tab of a browser.
- Includes the
document
andscreen
objects, which represent a site’s content and the shape of a device’s screen. - Contains global variables and functions.
Now rather than give a laundry list of window
object properties, here are 10 ways I’ve actually used the window
object.
1. Redirect to a new URL, open and close tabs
The location
object on window
can be used to jump URLs. This is done by simply reassigning it a new URL.
window.location.href = "https://www.google.com"
Often you’ll want to make this redirect conditional on clicking a button or other DOM element. In ReactJS, it can be done like this.
https://www.stephenhaledds.com/org/Sc-v-Gd1.html
https://www.stephenhaledds.com/org/Sc-v-Gd2.html
https://www.stephenhaledds.com/org/Sc-v-Gd3.html
https://www.stephenhaledds.com/org/Sc-v-Gd4.html
https://www.stephenhaledds.com/org/Sc-v-Gd5.html
https://www.stephenhaledds.com/org/Qn-v-St1.html
https://www.stephenhaledds.com/org/Qn-v-St2.html
https://www.stephenhaledds.com/org/Qn-v-St3.html
https://www.stephenhaledds.com/org/Qn-v-St4.html
https://www.stephenhaledds.com/org/Qn-v-St5.html
https://www.stephenhaledds.com/org/Qn-v-St6.html
https://www.stephenhaledds.com/org/Qn-v-St7.html
https://www.stephenhaledds.com/org/Qn-v-St8.html
https://www.stephenhaledds.com/org/Qn-v-St9.html
https://www.stephenhaledds.com/org/Qn-v-St10.html
https://www.stephenhaledds.com/org/Qn-v-An1.html
https://www.stephenhaledds.com/org/Qn-v-An2.html
https://www.stephenhaledds.com/org/Qn-v-An3.html
https://www.stephenhaledds.com/org/Qn-v-An4.html
https://www.stephenhaledds.com/org/Qn-v-An5.html
https://www.stephenhaledds.com/org/Nl-v-Mn1.html
https://www.stephenhaledds.com/org/Nl-v-Mn2.html
https://www.stephenhaledds.com/org/Nl-v-Mn3.html
https://www.stephenhaledds.com/org/Nl-v-Mn4.html
https://www.stephenhaledds.com/org/Nl-v-Mn5.html
https://www.stephenhaledds.com/org/Nl-v-Mn6.html
https://www.stephenhaledds.com/org/Nl-v-Mn7.html
https://www.stephenhaledds.com/org/Nl-v-Mn8.html
https://www.stephenhaledds.com/org/Nl-v-Mn9.html
https://www.stephenhaledds.com/org/Nl-v-Mn10.html
<Button
type="button"
onClick={(e) => {
window.location.href = `${thing.url}`;
}}>Visit</Button>
Sometimes we don’t want to lose the current page. This can be handled with the window.open()
method which opens a URL in a new tab.
window.open("https://www.w3schools.com")
It’s also just as easy to close the current tab.
window.close()
2. Implement infinite scrolling
Infinite scrolling refers to appending additional items to the DOM, as a user reaches the bottom of existing items. Infinitely scrolling is commonly implemented in views which render search results.
There are libraries for this…
But while I avoid not-invented-here syndrome, there’s no need to add the cruft of a whole library if you can solve a problem in 10 lines of code.
High level, we can implement infinite scrolling using the following 3 properties on window
.
// Distance you've scrolled from the top of a page
scrollHeight = window.document.documentElement.scrollTop// Current height of viewport
viewportHeight = window.innerHeight// Distance from top to bottom of a page
pageHeight = window.document.documentElement.scrollHeight
Given the above variables, we could write code which fires and loads more objects when the user has scrolled near the bottom of a page.
if (scrollHeight + viewportHeight + 50 > pageHeight){
// append more object
}
Hook this up to an event listener (we’ll get there in a minute) on the window
, and you’ve just rolled your own infinite scrolling.
There is a little more work to make this compatible with all browsers.
3. Access and manipulate DOM elements
The ability to manipulate the DOM is what makes JavaScript so awesome. It’s what let’s us build dynamic frontends.
What you may not know is that the document
object, which gives us access to the DOM, is a property on the window
object.
So when you’re calling this.
document.getElementById("header-title")
You are actually calling this.
window.document.getElementById("header-title");
4. Access information related to the current URL
We already touched on using location
to redirect, but it can do so much more.
When you call window.location
in the console, several properties are returned.
These can be used to determine which page the current user is now viewing.
Often, it’s useful to call and parse the pathname
so that we can conditionally fire logic when a user is on a specific page.
if ( window.location.pathname.includes("profile") ) {
// do something cool
}
5. Add event listeners on the window
Often we add event listeners to specific DOM elements.
But sometimes we want listeners directly on the window
itself.
In our above infinite scrolling example, we want to check the current scroll state anytime a user is scrolling.
This is a case for adding an event listener on the window
object. In React, you might wrap this in a useEffect
hook, like so.
useEffect(() => {
window.addEventListener(
'scroll',
someFunction
);
return () => window.removeEventListener('scroll', someFunction);
}, []
);
This will fire someFunction
anytime a user scrolls.
6. Trigger logic after a set amount of time or at a set interval
Sometimes you want to fire logic a specific amount of time after an event has occurred. For this, use setTimeout
.
You can try this in your browser console.
setTimeout(function(){ alert("Bonjour!"); }, 5000);
It will initiate a popup 5 seconds after running.
Now if you want to fire logic every 5 seconds, you can do the same thing with setInterval
.
Don’t actually run this in your console as it’s going to be extremely annoying when an alert pops up every 5 seconds.
setInterval(function(){ alert("Bonjour"); }, 5000);
This is a simple case using alerts. But a more complex case could be making an ajax request to the backend, to log information anytime a user views a page for more than 10 seconds.
7. Prompt, confirm, and alert popups
These popups definitely need some styling before deploying them into production, but they do have their use cases.
prompt()
can be used to ask the user for information and assign it to a variable.
var name = prompt("Who goes there?", "Your name...");
confirm()
is often used to check with a user before deleting something.
var d = confirm("Are you sure you want to delete your account?");
And alert()
is… well just an alert.
While it reeks of the web from the 90’s, there are times you’ll want a simple popup to communicate information to a user.
alert("Welcome to Hogwarts");
My only piece of advice is to please restyle these popups before using them!
8. Scrolling to a specific point on the page or by a specified number of pixels
There are times when you want to scroll a user to a specific point on a page. scrollTo()
can achieve this.
window.scrollTo(0, 1000);
This scrolls a user to 1000 pixels down from the top of the page. The arguments are the x and y pixel coordinates to scroll to, respectively.
For scrolling by a specific number of pixels, rather than to a specific point, use the scrollBy()
method.
window.scrollBy(0, window.innerHeight);
Again, the arguments are the number of pixels to scroll by horizontally and vertically.
9. The screen object
The screen object represents the currently viewable area.
Calling window.screen
in the console will return the following.
Screen can be useful if you decide to render objects differently depending on the width or height of the screen. For example:
if (window.screen.height < 800) {
// render fewer elements
}
What is the difference between "window.innerWidth”
and "screen.width”
?
Great question.
window.innerWidth
is the width of what is displayed in the browser, excluding bookmarks, the element inspector, etc.
screen.width
is the width of the resolution of your device’s screen.
10. window.console.log
Where would we be without console.log
to print variables and messages?
When you call this.
console.log('')
You are actually calling this.
window.console.log('Hello')
console
is also part of the window
object!
Conclusion
This list contains most of the ways I’ve found the window
object to be useful in my short JavaScript career.
It was fun digging into and understanding an object that I’ve been using but never took the time to play with.
I hope you found this as useful as writing it was to me.
Let us know in the comments if I missed any important or useful ways to use the window
object.
As always, keep coding!