Skip to content

Latest commit

 

History

History
109 lines (84 loc) · 2.08 KB

File metadata and controls

109 lines (84 loc) · 2.08 KB

Browser

  • 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;

redirect

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

Refresh a website

const refresh = () => window.location.reload();

getMyCoordinates

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,
    );
  }));