nhb-toolbox
Version:
A versatile collection of smart, efficient, and reusable utility functions, classes and types for everyday development needs.
65 lines (64 loc) • 2.07 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.smoothScrollTo = smoothScrollTo;
exports.toggleFullScreen = toggleFullScreen;
exports.copyToClipboard = copyToClipboard;
function smoothScrollTo(element, offset = 0) {
element.scrollIntoView({ behavior: 'smooth', block: 'start' });
if (offset !== 0) {
setTimeout(() => {
window.scrollBy({ top: offset, behavior: 'smooth' });
}, 300);
}
}
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();
}
}
}
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);
}
}
}