1

I want to do something before my page unloads so I'm trying to interrupt normal behaviour momentarily. I tried this but it doesn't seem to work:

document.onclick = function (e) {
  e = e || window.event;
  var element = e.target || e.srcElement;

  if (element.tagName == `a`) {
    document.body.classList.remove(`ready`);
    document.body.classList.add(`leaving`);

    setTimeout(function () {
      return true; // return false = prevent default action and stop event propagation
    }, 500);
  }
}

0.5s is the time I need to display a short css animation before leaving the page.

Gaetan L.
  • 649
  • 6
  • 20

1 Answers1

1

You can try the following code:

document.onclick = function (e) {
  e = e || window.event;
  var element = e.target || e.srcElement;
  if (element.tagName == `A`) {     // !uppercased
    e.preventDefault();             // prevent default anchor behavior
    var goTo = element.href;        // store target url

    document.body.classList.remove(`ready`);
    document.body.classList.add(`leaving`);

    setTimeout(function () {
      window.location = goTo;        // navigate to destination
    }, 500);
  }
}
yurzui
  • 205,937
  • 32
  • 433
  • 399
  • I tried your code but preventDefault doesn't seem to work as even when I remove the window.location live it still loads the next page. – Gaetan L. Apr 14 '20 at 19:17
  • Sorry my bad, I changed tagName == `A` from the original code to tagName == `a`, that's what stopped your code from working but now it's all good :) – Gaetan L. Apr 14 '20 at 19:37
  • 1
    Yes, I didn't pay attention on it:) Updated the answer – yurzui Apr 14 '20 at 19:37