Redirect user in 3 seconds

Posted in Snippets

A lot of times you need a simple permalink to distribute to your users for various external campaigns and such. You could do a redirect from https://robin.se/black-friday using the Redirection plugin. But this won’t trigger your Google Analytics or Facebook Pixel scripts. So you won’t be able to track the users and/or run remarketing ads.

The solution is not very classy, but it works. Simply wait a few seconds before doing the redirect so your scripts have time to send the necessary data.

(function() {
    var element = document.querySelector('.js-redirect'); // Element to display the countdown
    var seconds = 3; // Amount of seconds before redirecting
    if (element && element.dataset.url) {
        window.setInterval(function() {
            seconds = (seconds - 1); // Subtract one second
            if (seconds >= 0) {
                element.innerHTML = seconds; // Replace HTML with the current seconds
            } else {
                window.location.href = element.dataset.url; // Do the redirect
            }
        }, 1000);
    }
})();

Now all you need is something like this:

<p>You will be redirected in <span class="js-redirect" data-url="https://google.com">3</span> seconds.</p>

And it will count down from 3.

Leave a Comment