Page Transition (vanillaJS)

Adding a fade transition effect between pages can significantly enhance a website’s user experience by providing a smoother, more polished feel. Instead of abrupt page changes, the fade-out and fade-in effect adds a professional touch, making navigation appear seamless and visually appealing, which can help retain users and improve engagement.

This is a pure Javascript Version. If you want to see the WordPress version using jQuery please click here.

The Code

code iconJavaScript
1<script>
2      document.addEventListener("DOMContentLoaded", function () {
3
4        // Fade in the page when loaded
5        document.body.style.display = 'none';
6        fadeIn(document.body, 500);
7
8        // Add click event listeners to all links
9        var links = document.querySelectorAll('a');
10        links.forEach(function (link) {
11
12          link.addEventListener('click', function (event) {
13
14            var newUrl = link.getAttribute("href");
15
16            // Ignore anchors, mailto, and tel links
17            if (!newUrl || newUrl[0] === "#" || newUrl.startsWith("mailto:") || newUrl.startsWith("tel:")) {
18              return;
19            }
20
21            // Prevent default link behavior
22            event.preventDefault();
23
24            // Fade out the page
25            fadeOut(document.body, 500, function () {
26              // After fading out, redirect to the new page
27              window.location = newUrl;
28            });
29          });
30        });
31
32        // Fade in function
33        function fadeIn(element, duration) {
34          element.style.opacity = 0;
35          element.style.display = 'block';
36
37          var last = +new Date();
38          var tick = function () {
39            element.style.opacity = +element.style.opacity + (new Date() - last) / duration;
40            last = +new Date();
41
42            if (+element.style.opacity < 1) {
43              (window.requestAnimationFrame && requestAnimationFrame(tick)) || setTimeout(tick, 16);
44            }
45          };
46          tick();
47        }
48
49        // Fade out function
50        function fadeOut(element, duration, callback) {
51          element.style.opacity = 1;
52
53          var last = +new Date();
54          var tick = function () {
55            element.style.opacity = +element.style.opacity - (new Date() - last) / duration;
56            last = +new Date();
57
58            if (+element.style.opacity > 0) {
59              (window.requestAnimationFrame && requestAnimationFrame(tick)) || setTimeout(tick, 16);
60            } else {
61              if (typeof callback === 'function') {
62                callback();
63              }
64            }
65          };
66          tick();
67        }
68      });
69    </script>

2. How This Vanilla JavaScript Solution Works:

  • Fade In on Load:
    • The body is initially hidden (document.body.style.display = 'none';).
    • The fadeIn() function gradually changes the opacity of the body from 0 to 1 over the specified duration (500ms).
  • Fade Out on Link Click:
    • The fadeOut() function reduces the body’s opacity from 1 to 0 when an internal link is clicked.
    • After the fade-out completes, the page redirects to the clicked URL using window.location = newUrl;.
  • Ignoring External Links: The script skips #, mailto:, and tel: links, ensuring that only internal page links trigger the fade effect.

3. Understanding the Functions:

  • fadeIn(element, duration):
    • Fades in the given element (in this case, document.body) over a specified duration (500ms).
    • Uses requestAnimationFrame for smoother animations.
  • fadeOut(element, duration, callback):
    • Fades out the given element over a specified duration.
    • Once the fade-out is complete, the callback function is executed (which, in this case, redirects the user to the new page).

4. Customizing the Duration:

  • Change the value 500 in fadeIn(document.body, 500) or fadeOut(document.body, 500, ...) to adjust the transition speed. The value is in milliseconds (e.g., 500 means half a second).

5. Browser Support:

  • This solution works in all modern browsers. It uses requestAnimationFrame when available for smoother transitions but falls back to setTimeout if necessary.

Summary...

summ…

Date...

  • September 23, 2024

share...

tags...

Front-End DevJavascript
External resources