Home / Fading Page Transitions
Duplicate Snippet

Embed Snippet on Your Site

Fading Page Transitions

Fade out the page when clicking on any internal links.

20+
Code Preview
js
document.addEventListener("DOMContentLoaded", function() {
    // Create and insert CSS styles for fade-in and fade-out
    const style = document.createElement('style');
    style.innerHTML = `
        .fade-out {
            opacity: 0;
            transition: opacity 0.5s ease-in-out;
        }
        .fade-in {
            opacity: 1;
            transition: opacity 0.5s ease-in-out;
        }
    `;
    document.head.appendChild(style);
    // Apply the fade-in effect on page load
    document.body.classList.add('fade-in');
    // Attach event listeners to all internal links for the fade-out effect
    document.querySelectorAll('a').forEach(anchor => {
        anchor.addEventListener('click', function(event) {
            if (anchor.hostname !== window.location.hostname) return;
            event.preventDefault();
            const target = this.href;
            document.body.classList.remove('fade-in');
            document.body.classList.add('fade-out');
            setTimeout(function() {
                window.location.href = target;
            }, 500); // Match this duration with the CSS transition time
        });
    });
});

Comments

Add a Comment