karsttech.com/layouts/partials/background-images.html

95 lines
No EOL
2.8 KiB
HTML

{{ $images := slice }}
{{ range readDir "static/backgrounds" }}
{{ if or (in .Name ".webp") (in .Name ".jpg") }}
{{ $images = $images | append .Name }}
{{ end }}
{{ end }}
<div class="background-container" id="bg-container">
<img id="background-thumb" alt="Background" class="background-image">
<img id="background-full" alt="Background" class="background-image background-full" loading="lazy">
<div id="cursor-circle"></div>
<script>
const images = {{ $images }};
const randomImage = images[Math.floor(Math.random() * images.length)];
const thumbImg = document.getElementById('background-thumb');
const fullImg = document.getElementById('background-full');
const thumbPath = `/backgrounds/thumbs/${randomImage}`;
const fullPath = `/backgrounds/${randomImage}`;
thumbImg.src = thumbPath;
setTimeout(() => {
const preloadImg = new Image();
preloadImg.onload = () => {
fullImg.src = fullPath;
fullImg.classList.add('loaded');
setTimeout(() => thumbImg.remove(), 2000);
};
preloadImg.onerror = () => {
fullImg.src = fullPath;
fullImg.classList.add('loaded');
};
preloadImg.src = fullPath;
}, 800);
const container = document.getElementById('bg-container');
const circle = document.getElementById('cursor-circle');
let hoverTimer = null;
let revealTimer = null;
let isRevealed = false;
const isOverContent = (e) => {
const target = e.target;
return target.closest('article, header, nav, footer, section') !== null;
};
window.addEventListener('mousemove', (e) => {
circle.style.left = e.clientX + 'px';
circle.style.top = e.clientY + 'px';
if (isOverContent(e)) {
if (isRevealed || hoverTimer) {
resetEffect();
}
return;
}
if (isRevealed) return;
if (!hoverTimer) {
hoverTimer = setTimeout(() => {
circle.classList.add('active');
revealTimer = setTimeout(() => {
circle.classList.remove('active');
circle.classList.add('fade-out');
fullImg.classList.add('unblurred');
isRevealed = true;
}, 4000);
}, 1000);
}
});
const resetTimer = () => {
clearTimeout(hoverTimer);
clearTimeout(revealTimer);
hoverTimer = null;
revealTimer = null;
circle.classList.remove('active');
};
const resetEffect = () => {
resetTimer();
circle.classList.remove('fade-out');
fullImg.classList.remove('unblurred');
isRevealed = false;
};
document.addEventListener('mouseout', (e) => {
if (!e.relatedTarget && !e.toElement) {
resetEffect();
}
});
window.addEventListener('blur', resetTimer);
</script>
</div>