Before you leave

Don't forget to check out the source code on GitHub and Star it if you like! :)

To close this popup press Esc.

before-leaving-me.js

Do things before the user leaves your web page.

Download .zip Download .tar.gz View on GitHub

Demo

blm (before-leaving-me.js) creates a global named blm.

The code below will use blm to handle two things:

  • the moment when the user prepares to leave the page
  • the literal window closing (when the user closes the browser tab)
So, just try to close this tab with using the mouse.

// Listen for the page load
window.addEventListener("load", function () {

    // Select the box container element
    var boxContainerEl = document.querySelector(".box-container");

    // *before leaving me* display "Bye bye!"
    blm("Do you really want to leave?");

    // ...and "Hi", the current minute is odd
    blm(function (e) {
        if (new Date().getMinutes() % 2 === 1) {
            return "BTW, this is an odd minute.";
        }
    });

    // When *preparing to leave me* do something
    blm.prepare(function (e) {
        boxContainerEl.classList.add("active");
    });

    // Listen for the Esc key press
    window.addEventListener("keyup", function (e) {
        if (e.which === 27) {
            boxContainerEl.classList.remove("active");
        }
    });
});
Check out the documentation