0

I wanted to make a function that asks you if you really wanna leave the page when you try to leave, but where ever I press on my page it asks me this instead only when I try to leave, how do I fix it

The code:

document.addEventListener("DOMContentLoaded", function () {
    //Dialog
    document.addEventListener("click", function leave(){
        if(confirm("You sure you wanna leave this page?")){}
        else{
            alert("Staying on page"+ " " + document.title +".");
            event.preventDefault();
        } 
    });
DarkBee
  • 16,592
  • 6
  • 46
  • 58
Exch
  • 3
  • 1
  • 4

2 Answers2

0

You can use this code instead :-

window.onbeforeunload = function(e) {
  return "Do you want to exit this page?";
};

Note :- This would not work until the user interact with the web page

mplungjan
  • 169,008
  • 28
  • 173
  • 236
  • The browser does not allow any changes to the text. So `window.onbeforeunload = () => true;` or `window.addEventListener("beforeunload",()=>true)` – mplungjan May 08 '22 at 11:25
-1

You are binding the leave function to the click event, you should bind it to beforeunload event.

Fixed code:

document.addEventListener("DOMContentLoaded", function() {
  //Dialog
  document.addEventListener("beforeunload", function leave(event) {
    if (confirm("You sure you wanna leave this page?")) {} // do nothing
    else {
      alert("Staying on page" + " " + document.title + ".");
      event.preventDefault();
    }
  });
});
mplungjan
  • 169,008
  • 28
  • 173
  • 236
Daniel Botnik
  • 539
  • 1
  • 6
  • 20
  • But when I put "beforeunload" the page doesn't even ask me if I want to leave or not for some reason :/ – Exch May 08 '22 at 08:46
  • 1
    This code has multiple mistakes and will not work as expected. Alert and confirm prompts are ignored, must return an event.returnValue, and no reason to use DOMContentLoaded in this case because the listener can be attached to window. – Yogi May 08 '22 at 09:13