Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to dim the background when a confirm() is shown and turn dim off when user answers yes or no?

I found the similar question about using alert() but changing that to confirm() doesn’t work. Need to return the response. This results in the "Not confirmed" alert being displayed first. What do I need to do to fix this?

var originalConfirm = window.confirm;
window.confirm = function(args) {
  document.querySelector("html").classList.add("darkenPage");
  setTimeout(function() {
    var x = originalConfirm(args);
    document.querySelector("html").classList.remove("darkenPage");
    return (x);
  });
}
html.darkenPage {
  background-color: black;
}

html.darkenPage body {
  opacity: 0.6;
}
<button onclick="if (confirm('Hello World, yes or no')) { alert('Confirmed'); } else { alert('Not confirmed'); }  ">Confirm</button>

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

setTimeout runs the callback asynchronously, that means the return value inside the callback is not actually used, and the confirm function will return before the timeout callback is called. You’d need to use another callback as argument to confirm in order to get the response, but that would change the original API.

var originalConfirm = window.confirm;
window.confirm = function(args, callback) {
  document.querySelector("html").classList.add("darkenPage");
  setTimeout(function() {
    var x = originalConfirm(args);
    document.querySelector("html").classList.remove("darkenPage");
    callback(x);
  });
}
html.darkenPage {
  background-color: black;
}

html.darkenPage body {
  opacity: 0.6;
}
<button onclick="confirm('Hello World, yes or no', function (confirmed) { alert(confirmed ? 'Confirmed' : 'Not confirmed'); })">Confirm</button>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading