Auto Close Div Alert

by Paul Leech

HTML

<button id="d">Trigger Msgboxes</button>

CSS

body {
  background: #ccc;
}
#msgbox_alert {
  position: absolute;
  font-family: sans-serif;
  top: 40%;
  /* margin-top:100px; */
  left: 50%;
  margin-left: -180px;
  width: 360px;
  background-color: white;
  border: 2px #999 solid;
  border-radius: 0.5rem;
  padding: 2rem;
  box-shadow: 1px 1px 10px #999, 1.5px 1.5px 13.5px #ccc;
}
#msgbox_alert h2 {
  margin: -1.5rem 0.05rem 0.5rem -1.5rem;
  color: #fff;
  padding: 0.25rem;
  border-radius: 0.25rem;
  font-size: 1.15rem;
  width: 111%;
  text-shadow: 0.05rem 0.05rem 0.05rem #555, 0.06rem 0.06rem 0.06rem #111;
}
#msgbox_alert.warning h2 {
  background: #800;
}
#msgbox_alert.info h2 {
  background: #080;
}
#msgbox_alert.note h2 {
  background: #00c;
}
.warning {
  background: rgba(200, 0, 0, 0.5);
  color: #800;
}
.info {
  background: rgba(0, 200, 0, 0.95);
  color: #080;
}
.note {
  background: rgba(0, 0, 200, 0.95);
  color: #008;
}

.infowrap {
  border-radius: 50%;
  padding: 0.1rem 0.5rem;
  background-color: #fff;
  color: #080;
  font-size: 1rem;
  box-shadow: 0.05rem 0.05rem 0.05rem #555, 0.06rem 0.06rem 0.06rem #111;
}
.wrap {
  font-size: 1rem;
  margin: 0 0.25rem 0.95rem 0.5rem;
  text-shadow: 0.05rem 0.05rem 0.05rem #555, 0.06rem 0.06rem 0.06rem #111;
}

JavaScript

function msgBox(msg, duration = 2500, setclass = "info") {
  var el = document.createElement("div");
  el.setAttribute("id", "msgbox_alert");
  el.classList.add(setclass);
  let icon = "";
  if (setclass === "warning") {
    icon = "<span class='wrap'>⚠️</span>";
  } else if (setclass === "note") {
    icon = "<span class='wrap'>📝</span>";
  } else if (setclass === "info") {
    icon = "<span class='infowrap'>ℹ️</span>";
  }
  el.innerHTML = `<h2>${icon} ${setclass.toUpperCase()}</h2>`;
  el.innerHTML += msg;
  setTimeout(function () {
    el.parentNode.removeChild(el);
  }, duration);
  document.body.appendChild(el);
}

function delayMsgBox(delay = 2500, msg, duration = 2500, setclass = "info") {
  setTimeout(function () {
    msgBox(msg, duration, setclass);
  }, delay);
}

var d = document.getElementById("d");
d.onclick = function () {
  delayMsgBox(500, "Record Updated", 2500, (setclass = "info"));
  delayMsgBox(3000, "Record Deleted", 2500, (setclass = "warning"));
  delayMsgBox(5500, "Duly Noted!", 2500, (setclass = "note"));
};

delayMsgBox(500, "Record Updated", 2500, (setclass = "info"));
delayMsgBox(3000, "Record Deleted", 2500, (setclass = "warning"));
delayMsgBox(5500, "Duly Noted!", 2500, (setclass = "note"));

// msgBox("Record Deleted",2500, "info");
// msgBox("Friendly reminder",2500, "note");