Run Javascript only when comming from specific link

Viewed 65

I have this Javscript fade effect when opening the page, for example admin.php.

<body>
<script>
    document.body.className = 'fade';
</script>

...html code...

<script>
  document.addEventListener("DOMContentLoaded", function(e) {
    document.body.className = '';
  });
</script>
</body>

The problem is I can't figure it out how to run this script only when comming from login.php page.

For clarification, it's an effect when opening page it's white and then in about 1sec the page becomes visible, creating fade effect.

2 Answers

Pass along a variable in the query string. For example, link to it with admin.php?coming_from_login=1.

Then in your PHP file:

<?php if (isset($_GET['coming_from_login']) && $_GET['coming_from_login'] == '1'): ?>
<script>
  document.addEventListener("DOMContentLoaded", function(e) {
    document.body.className = '';
  });
</script>
<?php endif; ?>

You can make use of document.referrer:

<body>
    <script>
        const referrerPage = document.referrer.replace(location.origin, ""); // Remove the origin to leave just the page
        if (referrerPage === "/login.php") {
            document.body.className = 'fade';
            document.addEventListener("DOMContentLoaded", function (e) {
                document.body.className = '';
            });
        }
    </script>

    ...html code...
</body>
Related