- Notify on unsaved changes
window.addEventListener('beforeunload', (event) => {
event.preventDefault();
event.returnValue = '';
});- Copy content to the clipboard
const copyToClipboard = (content: string) => {
const textarea = document.createElement('textarea');
textarea.value = content;
document.body.appendChild(textarea);
textarea.select();
document.execCommand('Copy');
textarea.remove();
}- Scroll smoothly to the top of the page
const scrollToTop = () => {
const scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
if (scrollTop > 0) {
window.requestAnimationFrame(scrollToTop);
window.scrollTo(0, scrollTop - scrollTop / 8);
}
}- Check the preferred color scheme of the user
const prefersDarkColorScheme = () =>
window &&
window.matchMedia &&
window.matchMedia('(prefers-color-scheme: dark)').matches;- Smooth-scroll elements into view
const smoothScroll = (selector: string) =>
document
.querySelector(selector)
.scrollIntoView({ behavior: 'smooth' });- Check if the current tab is in view/focus
const isTabInView = () => document.hidden;- Check if an element is currently in focus
const isElementInFocus = (element: Element) => element === document.activeElement;Do a redirect to a specified URL
const redirect = (url: string, asLink = true) => {
if (asLink) {
window.location.href = url;
} else {
window.location.replace(url);
}
};Refresh a website
const refresh = () => window.location.reload();interface Coordinates {
latitude: number;
longitude: number;
}
const getMyCoordinates = (): Promise<Coordinates> => (
new Promise((resolve, reject) => {
navigator.geolocation.getCurrentPosition(
(position) => resolve({
latitude: position.coords.latitude,
longitude: position.coords.longitude,
}),
reject,
);
}));