Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

104
Views
How to fix this dialog spam on my page? - JavaScript

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();
        } 
    });
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

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

about 4 years ago · Juan Pablo Isaza Report

0

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();
    }
  });
});
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!