0

I'm using the custom alert below when page is about to close. The issue is that the alert pups up and the page closes before the user can click the OK button on the custom alert. What is missing is the custom alert that it cannot keep the page open till the user clicks the OK button?

window.onbeforeunload = function() {
   {
      return custom_alert(head, txt);
   }


function custom_alert(head, txt) {
  var d = document;
  var c_obj = d.getElementsByTagName("body")[0].appendChild(d.createElement("div"));
  c_obj.id = "contain";
  c_obj.style.height = d.documentElement.scrollHeight + "px";
  var alertObj = c_obj.appendChild(d.createElement("div"));
  alertObj.id = "alert";
  if (d.all && !window.opera)
    alertObj.style.top = document.documentElement.scrollTop + "px";
  alertObj.style.left = (d.documentElement.scrollWidth - alertObj.offsetWidth) / 2 + "px";
  alertObj.style.visiblity = "visible";
  var h1 = alertObj.appendChild(d.createElement("h1"));
  h1.appendChild(d.createTextNode(head));
  var msg = alertObj.appendChild(d.createElement("p"));
  msg.innerHTML = txt;
  var btn = alertObj.appendChild(d.createElement("a"));
  btn.id = "close";
  btn.appendChild(d.createTextNode('ok'));
  btn.focus();
  btn.onclick = function() {
    c_obj.parentNode.removeChild(c_obj);
  };
  alertObj.style.display = "block";
}
CodingSoft
  • 355
  • 5
  • 13
  • 4
    No, you are only creating a dom object (here a div) that mimicks the [window.confirm()](https://developer.mozilla.org/en-US/docs/Web/API/window/confirm) modal dialogue. This last does block execution of the program, yours doesn't – Kaiido Apr 19 '15 at 14:09
  • 1
    onbeforeunload is the only thing - you can't block anything with anything in the DOM. – Daniel A. White Apr 19 '15 at 14:09
  • 1
    `window.addEventListener('beforeunload',function(e){e.preventDefault();})` for example asks the user whether to close this page that could contain unsaved data. – Sebastian Simon Apr 19 '15 at 14:11
  • 1
    You can not show custom dialog. [Here][1] is a good explanation. [1]: http://stackoverflow.com/questions/6063522/dialog-box-runs-for-1-sec-and-disappears/6065085#6065085 – Yordan Ivanov Apr 19 '15 at 14:26

1 Answers1

0

I found a library that solves this problem:

http://t4t5.github.io/sweetalert/

The offical alert: alert("Oops... Something went wrong!");

The changed alert: sweetAlert("Oops...", "Something went wrong!", "error");

This library solves many of the problems of creating your own alert.

CleverSkull
  • 479
  • 3
  • 10