UNPKG

nhb-toolbox

Version:

A versatile collection of smart, efficient, and reusable utility functions, classes and types for everyday development needs.

60 lines (59 loc) 1.89 kB
export function smoothScrollTo(element, offset = 0) { element.scrollIntoView({ behavior: 'smooth', block: 'start' }); if (offset !== 0) { setTimeout(() => { window.scrollBy({ top: offset, behavior: 'smooth' }); }, 300); } } export function toggleFullScreen(element = document.documentElement) { const doc = document; const elem = element; if (!doc.fullscreenElement && !doc.webkitFullscreenElement) { if (elem.requestFullscreen) { elem.requestFullscreen(); } else if (elem.webkitRequestFullscreen) { elem.webkitRequestFullscreen(); } } else { if (doc.exitFullscreen) { doc.exitFullscreen(); } else if (doc.webkitExitFullscreen) { doc.webkitExitFullscreen(); } } } export async function copyToClipboard(text) { try { if (navigator?.clipboard?.writeText) { await navigator.clipboard.writeText(text); } else { const textArea = document.createElement('textarea'); textArea.value = text; textArea.style.position = 'fixed'; textArea.style.opacity = '0'; document.body.appendChild(textArea); textArea.select(); textArea.setSelectionRange(0, textArea.value?.length); const success = document.execCommand('copy'); document.body.removeChild(textArea); if (!success) { throw new Error('Cannot execute command in this environment!'); } } } catch (error) { console.error('Failed to copy text:', error); throw error; } finally { const textArea = document.querySelector('textarea[style*="fixed"]'); if (textArea) { document.body.removeChild(textArea); } } }