Useful APIs you probably don't know about
n0ruSh
Posted on October 10, 2022
In this post, I will cover some of the lesser known APIs that are useful for developers, with examples.
Fullscreen
To make elements to display themselves fullscreen, previously you could do it with css
position: fixed;
left: 0;
right: 0;
top: 0;
bottom: 0;
Things are getting easier with fullscreen API.
Use cases
- Creating a fullscreen video player or a fullscreen image viewer.
- Entering focus mode
Examples
<!-- html -->
<div id="wrapper">
<button id="full">Enter full screen</button>
<button id="exit">Exit full screen</button>
</div>
const container = document.getElementById("wrapper");
const triggerBtn = document.getElementById("full");
const exitBtn = document.getElementById("exit");
triggerBtn.addEventListener("click", () => {
// Go fullscreen
container.requestFullscreen();
});
exitBtn.addEventListener("click", () => {
// Exit fullscreen
container.exitFullscreen();
});
IntersectionObserver
Use cases
- Infinite scrolling
- Lazy loading images
- Event tracking
Examples
Hightlight images with border when they are fully visible on the screen. Previously to achieve this, you would have to do it in pull
way by keep checking the boundary of the images intervally. With the IntersectionObserver
API, you simply do the observation
with specified callback
and will get notified when it happens.
// Populate mock images into html
const container = document.getElementById("container");
for (let i = 0; i < 30; i++) {
const imgElement = document.createElement("img");
imgElement.src = "https://avatars.githubusercontent.com/u/7504237?v=4";
imgElement.dataset.index = i;
container.appendChild(imgElement);
}
// Specify the options for the observer (which mutations to observe)
let options = {
threshold: [0, 0.25, 0.5, 0.75, 1], // The timing of callback when intersetion reaches the threshold
};
// Create the observer
let observer = new IntersectionObserver((entries) => {
entries.forEach((entry) => {
if (entry.intersectionRatio === 1) {
entry.target.style.border = "1px solid teal";
} else {
entry.target.style.border = "none";
}
});
}, options);
let imgs = document.querySelectorAll("img");
for (let img of imgs) {
// Observe
observer.observe(img);
}
Page Visibility API
The Page Visibility API
triggers an event whenever the page visibility status changes (i.e. becomes visible or hidden)
Use cases
- Pause or resume a video when the page is hidden or visible
Examples
document.addEventListener("visibilitychange", function () {
if (document.visibilityState === "visible") {
// page is visible, resume video
} else {
// page is hidden, stop video
}
});
Web Share API
The Web Share API provides a mechanism for sharing text, links, files etc with sharing mechanisms of the underlying operating system.
Use cases
- Share content from your page to social media.
Examples
<!-- html -->
<body>
<button id="share">Share</button>
</body>
const shareBtn = document.getElementById("share");
const share = (data) => {
if (navigator.canShare(data)) {
return navigator.share(data);
}
throw new Error("The data is NOT shareable");
};
shareBtn.addEventListener("click", () => {
const shareData = {
title: "MDN",
text: "Learn web development on MDN!",
url: "https://developer.mozilla.org",
};
share(shareData);
});
Number.prototype.toString
The toString
method returns a string representatino of the specified number.
Use cases
- Get unicode representation of a number
Example
let s = "你";
let codePoint = s.charCodeAt(0);
console.log(codePoint); // 20320
let hex = codePoint.toString(16); // to hex format
console.log(hex); // 4f60
console.log(String.fromCharCode("0x4f60", 20320)); // 你你
console.log("\u4f60"); // 你
JSON.stringify(value[, replacer[, space]])
The JSON.stringify
method converts a JavaScript value to a JSON string.
Use cases
- Replace or filter values with a
replacer
argument, to avoid beforehand manipulation with original data. - Beautify the output with
space
argument
Examples
// Replacer is a function - apply replacer before stringify the value
JSON.stringify(
{
a: 4,
b: [3, 5, "hello"],
},
(key, val) => {
if (typeof val === "number") {
return val * 2;
}
return val;
}
); //{"a":8,"b":[6,10,"hello"]}
// Replacer is an array - use replacer as a white list to filter the keys
JSON.stringify(
{
a: 4,
b: {
a: 5,
d: 6,
},
c: 8,
},
["a", "b"]
); //{"a":4,"b":{"a":5}}
JSON.stringify(
{
a: [3, 4, 5],
b: "hello",
},
null,
"|--\t"
);
/**
{
|-- "a": [
|-- |-- 3,
|-- |-- 4,
|-- |-- 5
|-- ],
|-- "b": "hello"
}
*/
Date.prototype.getDate
Returns the day of the month for the specified date according to local time.
Use cases
- Get the number of days in a month
Examples
// The 0th day of next month is the last day of the current month.
function daysInMonth(year, month) {
let date = new Date(year, month + 1, 0);
return date.getDate();
}
/**
* Note that date month in JS starts with 0
*/
// How many days in March 2017
console.log(daysInMonth(2017, 2)); // 31
// How many days in Feb 2017
console.log(daysInMonth(2017, 1)); // 28
// How many days in Feb 2016
console.log(daysInMonth(2016, 1)); // 29
Posted on October 10, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.