A major part of JavaScript is the ability to target specific parts of the DOM such as an element, class, ID, or integral browser component.
The term Global Window Object represents the browser window. You can access things inside it or its own built-in methods. Common ones are listed below but a full list is available in the MDN developer documentation.
Pop-ups
window.alert('message')
This window method causes a pop up to appear in the browser containing 'message'. A good use case of this for when you need to display information to the user such as an error occurring or perhaps a confirmation message when a form has been submitted or similar action completed.
HTML
<button id="window-alert-example-button-id">
Press here to show an example window alert.
</button>
JavaScript
// Check that the document has loaded first
document.addEventListener('DOMContentLoaded', function () {
// Get the button as a variable by targeting the ID
const exampleButton = document.getElementById('window-alert-example-button-id')
// Add an event listener to the button to check for a click
exampleButton.addEventListener('click', function() {
// Add a function that shows the alert
window.alert('Button Clicked!');
})
});
Result
window.prompt('Prompt text')
This window method opens up a dialogue box for the user to enter some information. It will return the string of whatever the user enters or null if it is cancelled.
HTML
<button id="window-prompt-example-button-id">
Press here to show an example window prompt.
</button>
JavaScript
// Check that the document has loaded first
document.addEventListener('DOMContentLoaded', function () {
// Get the button as a variable by targeting the ID
const exampleButton = document.getElementById('window-prompt-example-button-id')
// Add an event listener to the button to check for a click
exampleButton.addEventListener('click', function() {
// Add a function that shows the prompt
// Save the user response to a variable
let userResponse = window.prompt('Enter a prompt!');
// Do something with the response
earlierDefinedFunction(userResponse);
})
});
Result
window.confirm('Confirmation Message')
This window method opens a pop up for the user to confirm or cancel something. It returns true if confirmed or false if cancelled.
HTML
<button id="window-confirm-example-button-id">
Press here to show an example window confirmation.
</button>
JavaScript
// Check that the document has loaded first
document.addEventListener('DOMContentLoaded', function () {
// Get the button as a variable by targeting the ID
const exampleButton = document.getElementById('window-confirm-example-button-id')
// Add an event listener to the button to check for a click
exampleButton.addEventListener('click', function() {
// Add a function that shows the prompt
// Save the user response to a variable
let userResponse = window.confirm('Confirm?')
// Do something with the response
earlierDefinedFunction(userResponse);
})
});
Result
Window Dimensions
In some cases you may want to us the window dimensions, this is the syntax for accessing it. The examples follow syntax for sections not yet covered but they follow the process of assign the value to a variable, get the element that will show the result, and set that element's content to the variable.
window.innerWidth
and
window.innerHeight
These return the viewport size including scroll bars but not toolbars or menus.
HTML
<button id="window-inner-example-button-id" class="site-button">
Press here to show the window inner heights and width.
</button>
<div>
<p>The window inner width is:<span id="window-inner-width-result-id"></span>.</p><br>
<p>The window inner height is:<span id="window-inner-height-result-id"></span>.</p>
</div>
JavaScript
// Check that the document has loaded first
document.addEventListener('DOMContentLoaded', function () {
// Get the button as a variable by targeting the ID
const exampleButton = document.getElementById('window-inner-example-button-id');
// Add an event listener to the button to check for a click
exampleButton.addEventListener('click', function() {
// Add a function
// Get the result spans
let innerWidthResultSpan = document.getElementById('window-inner-width-result-id');
let innerHeightResultSpan = document.getElementById('window-inner-height-result-id');
// Get the height and width
const innerWindowWidth = window.innerWidth;
const innerWindowHeight = window.innerHeight;
// Set the contents of the result spans to the height and width results
innerWidthResultSpan.innerHTML = innerWindowWidth;
innerHeightResultSpan.innerHTML = innerWindowHeight;
})
});
Result
The window inner width is: ? pixels.
The window inner height is: ? pixels.
window.outerWidth
and
window.outerHeight
These return the total window size including browser interfaces such as menus
HTML
<button id="window-outer-example-button-id" class="site-button">
Press here to show the window outer heights and width.
</button>
<div>
<p>The window outer width is:<span id="window-outer-width-result-id"></span>.</p><br>
<p>The window outer height is:<span id="window-outer-height-result-id"></span>.</p>
</div>
JavaScript
// Check that the document has loaded first
document.addEventListener('DOMContentLoaded', function () {
// Get the button as a variable by targeting the ID
const exampleButton = document.getElementById('window-outer-example-button-id');
// Add an event listener to the button to check for a click
exampleButton.addEventListener('click', function() {
// Add a function
// Get the result spans
let outerWidthResultSpan = document.getElementById('window-outer-width-result-id');
let outerHeightResultSpan = document.getElementById('window-outer-height-result-id');
// Get the height and width
const outerWindowWidth = window.outerWidth;
const outerWindowHeight = window.outerHeight;
// Set the contents of the result spans to the height and width results
outerWidthResultSpan.innerHTML = outerWindowWidth;
outerHeightResultSpan.innerHTML = outerWindowHeight;
})
});
Result
The window outer width is: ? pixels.
The window outer height is: ? pixels.
URL and Navigation
It's handy on occasion to be able to get the data from the URL for confirmation or browser manipulation.
window.location
This gives full access to the URL info as a location object. You can use
window.location.href
to get the full URL from the current page along with
hostname,
pathname,
protocol,
search
etc. to get different specific information.
HTML
<button id="window-location-example-button-id" class="site-button">
Press here to show the URL information.
</button>
<div>
<p>The full URL information is: <span id="window-location-full-result-id">?</span>.</p><br>
<p>The current page is: <span id="window-location-current-result-id">?</span>.</p>
</div>
JavaScript
// Check that the document has loaded first
document.addEventListener('DOMContentLoaded', function () {
// Get the button as a variable by targeting the ID
const exampleButton = document.getElementById('window-location-example-button-id');
// Add an event listener to the button to check for a click
exampleButton.addEventListener('click', function() {
// Add a function
// Get the result spans
let fullInformationResultSpan = document.getElementById('window-location-full-result-id');
let currentPageResultSpan = document.getElementById('window-location-current-result-id');
// Get the URL information
const fullInformation = window.location;
const currentPage = window.location.href;
// Set the contents of the result spans to the height and width results
fullInformationResultSpan.innerHTML = fullInformation;
currentPageResultSpan.innerHTML = currentPage;
})
});
Result
The full URL information is: ?.
The current page is: ?.
window.history
This represents the session history of the browser tab. You can use
window.history.back
or
window.history.forward
to move the page back or forward one just like the back and forward buttons in your browser. Due to security
concerns, you cannot get a list of your URL history through JavaScript.
HTML
<button id="window-history-example-button-id" class="site-button">
Press here to show your window history information.
</button>
<div>
<p>Your window history information is:</p>
<ul id="window-history-result-id"></ul>
</div>
JavaScript
// Check that the document has loaded first
document.addEventListener('DOMContentLoaded', function () {
// Get the button as a variable by targeting the ID
const exampleButton = document.getElementById('window-history-example-button-id')
// Add an event listener to the button to check for a click
exampleButton.addEventListener('click', function() {
console.log("Button pressed")
// Add a function
// Get the result unordered list
let historyInformationList = document.getElementById('window-history-result-id');
// Get the history information
const historyInformation = window.history;
// Clear previous content
historyInformationList.innerHTML = '';
// Loop through the properties of the history object
for (let key in historyInformation) {
// Create a list element
const li = document.createElement('li');
// Add the information to the list element
li.textContent = `${key}: ${historyInformation[key]}`;
console.log('Pressed')
// Add the list element to the unordered list
historyInformationList.appendChild(li);
}
})
});
Result
Your window history information is:
Data Storage
window.localStorage
This stores key, value pairs in the browser that stay there after the page is closed. These are used mainly for user preferences. In fact, I use them on this website for the light/dark mode toggle. Otherwise going to a new page would reset it to light mode. My code for this functionality is:
// Make sure that the document has loaded
document.addEventListener("DOMContentLoaded", function () {
// Get the day/night select buttons from the dropdown
const dayButton = document.getElementById("day-mode");
const nightButton = document.getElementById("night-mode");
// Get the dropdown itself
const modeToggleButton = document.getElementById(
"day-mode-toggle-dropdown"
);
// Highlight JS CDN links (this changes the day/night mode of the code examples)
const hightlightJsCDN = document.getElementById('highlightjscdn');
// Create a function to set the initial mode
function setSelectedMode(mode) {
// If the mode has the value of the fontawesome sun icon passed into it
if (mode === "<i class='fa-solid fa-sun'></i>") {
// Add the active class to the day button
dayButton.classList.add("active");
// Remove the active class from the night button
nightButton.classList.remove("active");
// Set the toggle button to show the day mode
modeToggleButton.html = "<i class='fa-solid fa-sun'></i>";
// Update the day/night mode of the code examples
hightlightJsCDN.setAttribute('href', 'https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/styles/default.min.css');
// Otherwise if function is run without the fontawesome sun icon
} else {
// Add active class to the night button
nightButton.classList.add("active");
// Remove active class from the day button
dayButton.classList.remove("active");
// Change the drop down button to show a mood
modeToggleButton.html = "<i class='fa-solid fa-moon'></i>";
// Update the day/night mode of the code examples
hightlightJsCDN.setAttribute('href', 'https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/styles/atom-one-dark.min.css');
}
}
// Event listeners for changing modes
// If the day mode button is clicked
dayButton.addEventListener("click", function () {
// Remove night-mode class from the body element
document.body.classList.remove("night-mode");
// Add day-mode class to the body element
document.body.classList.add("day-mode");
// Save the preference as the key:value of theme: day
localStorage.setItem("theme", "day");
// Run the setSelectedMode function with the fontawesome sun icon
setSelectedMode("<i class='fa-solid fa-sun'></i>");
// Update the day/night mode of the code examples
hightlightJsCDN.setAttribute('href', 'https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/styles/default.min.css');
});
// If the night mode button is clicked
nightButton.addEventListener("click", function () {
// Remove day-mode class from the body element
document.body.classList.remove("day-mode");
// Add night-mode class to the body element
document.body.classList.add("night-mode");
// Save the preference as the key:value of theme: night
localStorage.setItem("theme", "night");
// Run the setSelectedMode function with the fontawesome oon icon
setSelectedMode("<i class='fa-solid fa-moon'></i>");
// Update the day/night mode of the code examples
hightlightJsCDN.setAttribute('href', 'https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/styles/atom-one-dark.min.css');
});
// Initialize each page with the chosen mode
// Use localstorage to get the value from the key "theme"
const storedTheme = localStorage.getItem("theme");
// If the value is night
if (storedTheme === "night") {
// Add night-mode class to the body
document.body.classList.add("night-mode");
// Remove day-mode class from the body
document.body.classList.remove("day-mode");
// Run setSelectedMode with the fontawesome moon icon
setSelectedMode("<i class='fa-solid fa-moon'></i>");
// Update the day/night mode of the code examples
hightlightJsCDN.setAttribute('href', 'https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/styles/atom-one-dark.min.css');
} else {
// If the value is not night
// Add day-mode class to the body
document.body.classList.add("day-mode");
// Remove night-mode class from the body
document.body.classList.remove("night-mode");
// Run setSelectedMode with the fontawesome sun icon
setSelectedMode("<i class='fa-solid fa-sun'></i>");
// Update the day/night mode of the code examples
hightlightJsCDN.setAttribute('href', 'https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/styles/default.min.css');
}
});