alerts.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. function addAlert(
  2. addToEl, alertMessage,
  3. type = "primary",
  4. timeout = 5,
  5. info = undefined,
  6. onAdd, onClose
  7. ) {
  8. function setAttributes(el, attrs) {
  9. if (!attrs)
  10. return;
  11. for (var key in attrs)
  12. el.setAttribute(key, attrs[key]);
  13. }
  14. function addElement({
  15. tag = "div", parent = null,
  16. classes = [], attrs = {},
  17. innerText = null,
  18. children = []
  19. } = {}) {
  20. let result = document.createElement(tag);
  21. result.innerText = innerText;
  22. result.classList.add(...classes);
  23. setAttributes(result, attrs)
  24. parent?.appendChild(result);
  25. result.append(...(children?.filter(c => c) ?? []));
  26. return result;
  27. }
  28. if (!info && ["success", "danger", "warning", "info"].includes(type.toLowerCase()))
  29. info = type.charAt(0).toUpperCase() + type.slice(1);
  30. let alertDiv = null;
  31. addElement(
  32. {
  33. parent: addToEl, classes: ["container"],
  34. children:
  35. [
  36. alertDiv = addElement(
  37. {
  38. classes: ["alert", "alert-" + type, "alert-dismissible", "fade", "show"], role: "alert",
  39. children:
  40. [
  41. info ? addElement({tag: "strong", innerText: info + " "}) : null,
  42. addElement({tag: "a", innerText: alertMessage}),
  43. addElement({ tag: "button", classes: ["btn-close"], attrs: {"type": "button", "data-bs-dismiss": "alert", "aria-label": "Close" }})
  44. ]
  45. })
  46. ]
  47. });
  48. if (onClose)
  49. alertDiv.addEventListener("closed.bs.alert", onClose);
  50. if (onAdd)
  51. onAdd();
  52. if (timeout > 0)
  53. {
  54. var bootstrapAlert = new bootstrap.Alert(alertDiv);
  55. setTimeout(() => bootstrapAlert.close(), timeout * 1000);
  56. }
  57. }