❇️ Various DOM Access

Scroll to element

/**
 * @param targetId <string> Id of the Element
 * @param additionalSpacing <number> - Optional. Additional spacing from the top
 */
export const scrollToDomId = (targetId: string, additionalSpacing = 0) => {
  const element = document.getElementById(targetId)
 
  if (!!element) {
    const elementPosition = element.getBoundingClientRect().top
    const offsetPosition = elementPosition + window.pageYOffset - additionalSpacing
 
    requestAnimationFrame(() => {
      window.scrollTo({
        top: offsetPosition,
        behavior: 'smooth',
      })
    })
  }
}

Download from Blob

/**
 * @param blob <Blob>
 * @param filename <string>
 */
export function downloadBlob(blob: Blob, filename: string) {
  if (typeof URL.createObjectURL === 'function') {
    const safeFileName = filename.replace(/\//g, '_')
    // Convert your blob into a Blob URL (a special url that points to an object in the browser's memory)
    const blobUrl = URL.createObjectURL(blob)
 
    // Create a link element
    const link = document.createElement('a')
 
    // Set link's href to point to the Blob URL
    link.href = blobUrl
    link.download = safeFileName
    link.setAttribute('data-filename', safeFileName)
    link.style.display = 'none'
 
    // Append link to the body
    document.body.appendChild(link)
 
    // Dispatch click event on the link
    // This is necessary as link.click() does not work on the latest firefox
    link.dispatchEvent(
      new MouseEvent('click', {
        bubbles: true,
        cancelable: true,
        view: window,
      })
    )
 
    // Remove link from body
    document.body.removeChild(link)
    // Revoke after usage
    URL.revokeObjectURL(blobUrl)
  }
}