Suggestions for improving this code - same exact functionality
const Prompts = (function () {
let modalOpen = false;
let previouslyFocusedElement = null;
function createButton(label, onClick, type = "button") {
const btn = document.createElement("button");
applyStyles(btn, buttonStyle);
btn.type = type;
btn.textContent = label;
if (onClick) {
btn.addEventListener("click", onClick);
}
return btn;
}
function showModal(overlay, onClose) {
if (modalOpen) return; // Prevent multiple modals
modalOpen = true;
code
Assistant
User
That doesn't work - hitting OK or cancel on the confirm() and prompt() dialogs always acts as if cancel was clicked - also it doesn't focus the elements such that hitting "enter" on the confirm() dialog is the same as hitting OK
Assistant
User
I don't think you used HTML dialog.showModal() in that at all
Assistant
previouslyFocusedElement = document.activeElement;
document.body.appendChild(overlay);
// Focus trap and ESC handler
const focusableElements = overlay.querySelectorAll(
'button, input, [href], select, textarea, [tabindex]:not([tabindex="-1"])',
);
const firstFocusable = focusableElements[0];
const lastFocusable = focusableElements[focusableElements.length - 1];
function keyHandler(e) {
if (e.key === "Escape") {
e.preventDefault();
cleanup();
onClose("escape");
} else if (e.key === "Tab") {
// Focus trapping
if (focusableElements.length === 1) {
<URL>eventDefault(); // Only one focusable element, cycle back to it.
} else {
if (e.shiftKey && document.activeElement === firstFocusable) {
// If Shift+Tab on first element, go to last
<URL>eventDefault();
lastFocusable.focus();
} else if (!e.shiftKey && document.activeElement === lastFocusable) {
// If <REDACTED> on last element, go to first
<URL>eventDefault();
firstFocusable.focus();
}
}
}
}
<URL>dEventListener("keydown", <REDACTED>);
function cleanup() {
document.removeEventListener("keydown", <REDACTED>);
if (overlay.parentNode) {
document.body.removeChild(overlay);
}
modalOpen = false;
if (previouslyFocusedElement && previouslyFocusedElement.focus) {
previouslyFocusedElement.focus();
}
}
return { cleanup, firstFocusable, focusableElements };
}
async function alert(message) {
return new Promise((resolve) => {
const { overlay, form } = createModal(message);
Below are some suggestions and refactoring ideas to improve the code while maintaining the same functionality. These suggestions aim to make the code more modular, more readable, and potentially more accessible and maintainable:
Modularize Repeated CodeCertain operations such as creating a button row, applying styles, and handling focus trapping and cleanup are repeated across thealert,confirm, andpromptfunctions. Consider creating helper functions to DRY (Don’t Repeat Yourself) up the code:A dedicated function for creating the button row could simplify the main modal creation functions.A singleattachFocusTrapfunction could handle the focus trapping and cleanup.AshowModalfunction is already present, but you could break out its logic further if needed.
A dedicated function for creating the button row could simplify the main modal creation functions.
A singleattachFocusTrapfunction could handle the focus trapping and cleanup.
AshowModalfunction is already present, but you could break out its logic further if needed.
Separate Styling and LogicCurrently, styles are defined as JavaScript objects and applied inline. While this is fine for a self-contained component, it might be cleaner to:Move styles into a dedicated style object or even external CSS (depending on the environment).Keep the code focused on functionality rather than mixing logic and style.
Move styles into a dedicated style object or even external CSS (depending on the environment).
Keep the code focused on functionality rather than mixing logic and style.
Add ARIA Attributes for AccessibilityAdding basic ARIA attributes and roles can make the modals more accessible:Addrole="dialog"to the modal container.Addaria-modal="true"to indicate that the background is not interactable.Associate the message content witharia-labelledbyoraria-describedbyto improve screen reader support.
Addrole="dialog"to the modal container.
Addaria-modal="true"to indicate that the background is not interactable.
Associate the message content witharia-labelledbyoraria-describedbyto improve screen reader support.
Use More Descriptive Function and Variable NamesFor example:createModalcould returnmodalElementswhich containsoverlay,form,msg, etc.RenamemsgtomessageElement.
createModalcould returnmodalElementswhich containsoverlay,form,msg, etc.
RenamemsgtomessageElement.
Consistent Error/Cancel HandlingThe code is currently consistent but you might consider a unified error/cancel cleanup approach or a single utility that gracefully handles cleanup and resolution.
Focus Management EnhancementsThe focus trapping is good, but you might consider:Automatically focus the first focusable element if there is no explicitly preferred element to focus.Add comments explaining why and how focus is trapped and returned.
Automatically focus the first focusable element if there is no explicitly preferred element to focus.
Add comments explaining why and how focus is trapped and returned.
UseconstandletAppropriatelyMake sure all variables that do not change references are declared withconst. For example, since styles do not change after definition, they should beconst.
Optional: Add Animation or TransitionsAlthough not necessary, you could improve the user experience by adding simple fade-in/out transitions.
Modularize Repeated CodeCertain operations such as creating a button row, applying styles, and handling focus trapping and cleanup are repeated across thealert,confirm, andpromptfunctions. Consider creating helper functions to DRY (Don’t Repeat Yourself) up the code:
A dedicated function for creating the button row could simplify the main modal creation functions.
A singleattachFocusTrapfunction could handle the focus trapping and cleanup.
AshowModalfunction is already present, but you could break out its logic further if needed.
A dedicated function for creating the button row could simplify the main modal creation functions.
A singleattachFocusTrapfunction could handle the focus trapping and cleanup.
AshowModalfunction is already present, but you could break out its logic further if needed.
Separate Styling and LogicCurrently, styles are defined as JavaScript objects and applied inline. While this is fine for a self-contained component, it might be cleaner to:
Move styles into a dedicated style object or even external CSS (depending on the environment).
Keep the code focused on functionality rather than mixing logic and style.
Move styles into a dedicated style object or even external CSS (depending on the environment).
Keep the code focused on functionality rather than mixing logic and style.
Add ARIA Attributes for AccessibilityAdding basic ARIA attributes and roles can make the modals more accessible:
Addrole="dialog"to the modal container.
Addaria-modal="true"to indicate that the background is not interactable.
Associate the message content witharia-labelledbyoraria-describedbyto improve screen reader support.
Addrole="dialog"to the modal container.
Addaria-modal="true"to indicate that the background is not interactable.
Associate the message content witharia-labelledbyoraria-describedbyto improve screen reader support.
Use More Descriptive Function and Variable NamesFor example:
createModalcould returnmodalElementswhich containsoverlay,form,msg, etc.
RenamemsgtomessageElement.
createModalcould returnmodalElementswhich containsoverlay,form,msg, etc.
RenamemsgtomessageElement.
Consistent Error/Cancel HandlingThe code is currently consistent but you might consider a unified error/cancel cleanup approach or a single utility that gracefully handles cleanup and resolution.
Focus Management EnhancementsThe focus trapping is good, but you might consider:
Automatically focus the first focusable element if there is no explicitly preferred element to focus.
Add comments explaining why and how focus is trapped and returned.
Automatically focus the first focusable element if there is no explicitly preferred element to focus.
Add comments explaining why and how focus is trapped and returned.
UseconstandletAppropriatelyMake sure all variables that do not change references are declared withconst. For example, since styles do not change after definition, they should beconst.
Optional: Add Animation or TransitionsAlthough not necessary, you could improve the user experience by adding simple fade-in/out transitions.
Maintains the exact same functionality and logic flow.
Improves code organization by extracting repetitive logic into helper functions.
Enhances accessibility by adding attributes.
Simplifies style application by usingObject.assign.
Better readability and maintainability.
Maintains the exact same functionality and logic flow.
Improves code organization by extracting repetitive logic into helper functions.
Enhances accessibility by adding attributes.
Simplifies style application by usingObject.assign.
Better readability and maintainability.
All these changes preserve the original behavior while making the code cleaner and slightly more accessible.
The issue arises primarily because the proposed refactoring introduced a pattern where callingcleanup()inside the form submission handler also triggered theonClose()callback—causing both OK and Cancel actions (and even Enter keypresses) to end up being treated as a "cancel" scenario.
Key Problems and How to Fix Them:
cleanup()Should Not Always TriggeronClose():In the refactored version,cleanup()was callingonClose()unconditionally, causing the promise to resolve to the "cancel" value even when the user clicked "OK" or pressed Enter.cleanup()should be focused solely on removing the modal from the DOM and restoring focus, not resolving the promise. The decision to resolve or reject should be left to the event handlers that callcleanup().
Focus and Enter Key Submission:Ensure that the OK button is a submit button (type="submit") and that when the user presses Enter, it triggersform.onsubmitand resolvestruein theconfirm()dialog. Also ensure the correct element is focused after showing the modal.
Keeping the Original Control Flow foronClose():The original code handled the ESC key and focus trapping internally, without forcingonCloseto always override the decision. Restore this logic so that ESC simply resolves as cancel, while form submission resolves as OK.
cleanup()Should Not Always TriggeronClose():In the refactored version,cleanup()was callingonClose()unconditionally, causing the promise to resolve to the "cancel" value even when the user clicked "OK" or pressed Enter.cleanup()should be focused solely on removing the modal from the DOM and restoring focus, not resolving the promise. The decision to resolve or reject should be left to the event handlers that callcleanup().
Focus and Enter Key Submission:Ensure that the OK button is a submit button (type="submit") and that when the user presses Enter, it triggersform.onsubmitand resolvestruein theconfirm()dialog. Also ensure the correct element is focused after showing the modal.
Keeping the Original Control Flow foronClose():The original code handled the ESC key and focus trapping internally, without forcingonCloseto always override the decision. Restore this logic so that ESC simply resolves as cancel, while form submission resolves as OK.
Below is a revised version of the suggested improvements. It maintains the original logic more closely while still improving modularity and readability. The key change is thatonCloseis only called for forced closures (like ESC), not during normal form submission.
javascriptCopy codeconst Prompts = (function () {
let modalOpen = false;
let previouslyFocusedElement = null;
// Common styles as constants
const overlayStyle = { /* ... same as original ... / };
const modalStyle = { / ... same as original ... / };
const messageStyle = { / ... same as original ... / };
const buttonRowStyle = { / ... same as original ... / };
const buttonStyle = { / ... same as original ... / };
const inputStyle = { / ... same as original ... */ };
function applyStyles(element, styles) {
Object.assign(element.style, styles);
}
async function confirm(message) {
return new Promise((resolve) => {
const { overlay, form } = createModal(message);
code
const buttonRow = document.createElement("div");
applyStyles(buttonRow, buttonRowStyle);
const cancelBtn = createButton("Cancel", (e) => {
e.preventDefault();
cleanup();
resolve(false);
}, "button", { backgroundColor: "#6c757d" });
const okBtn = createButton("OK", null, "submit");
buttonRow.appendChild(cancelBtn);
buttonRow.appendChild(okBtn);
form.appendChild(buttonRow);
form.onsubmit = (e) => {
e.preventDefault();
cleanup();
resolve(true);
};
const { cleanup, focusableElements } = showModal(overlay);
// ESC key should be treated as cancel
<URL>dEventListener("keydown", function escHandler(e) {
if (e.key === "Escape") {
<URL>eventDefault();
document.removeEventListener("keydown", <REDACTED>);
cleanup();
resolve(false);
}
});
// Focus on the OK button (second button) so pressing Enter triggers submit
if (focusableElements && focusableElements.length > 1) {
focusableElements[1].focus();
}
});
}
async function prompt(message) {
return new Promise((resolve) => {
const { overlay, form } = createModal(message);
code
const input = document.createElement("input");
applyStyles(input, inputStyle);
input.type = "text";
input.name = "promptInput";
form.appendChild(input);
const buttonRow = document.createElement("div");
applyStyles(buttonRow, buttonRowStyle);
const cancelBtn = createButton("Cancel", (e) => {
e.preventDefault();
cleanup();
resolve(null);
}, "button", { backgroundColor: "#6c757d" });
const okBtn = createButton("OK", null, "submit");
buttonRow.appendChild(cancelBtn);
buttonRow.appendChild(okBtn);
form.appendChild(buttonRow);
form.onsubmit = (e) => {
<URL>eventDefault();
const val = input.value;
cleanup();
resolve(val);
};
const { cleanup } = showModal(overlay);
// ESC key should cancel
<URL>dEventListener("keydown", function escHandler(e) {
if (e.key === "Escape") {
<URL>eventDefault();
document.removeEventListener("keydown", <REDACTED>);
cleanup();
resolve(null);
}
});
// Focus the input field so user can type immediately
input.focus();
});
}
return { alert, confirm, prompt };
})();
What Changed?
Removed the direct call toonClose()insidecleanup(). Nowcleanup()just cleans up the DOM and focus.
Handled the ESC key press separately, just like the original code, ensuring that hitting ESC resolves the promise as cancel without interfering withokactions.
Ensured that the submit (OK) button is focused, making pressing Enter behave correctly.
Maintained the same top-level logic for resolving the promise as in the original code.
Removed the direct call toonClose()insidecleanup(). Nowcleanup()just cleans up the DOM and focus.
Handled the ESC key press separately, just like the original code, ensuring that hitting ESC resolves the promise as cancel without interfering withokactions.
Ensured that the submit (OK) button is focused, making pressing Enter behave correctly.
Maintained the same top-level logic for resolving the promise as in the original code.
This approach should fix the issues whereOKandCancelboth acted as cancel and also restore proper Enter key handling.
You're correct; the previous examples didn't use the HTMLelement or itsshowModal()method. Theelement provides built-in modal functionality, including focus management and some accessibility considerations, which can simplify the code and reduce the need to manually manage overlays and focus trapping.
Below is an example of how you can implementalert,confirm, andpromptfunctionality using theelement andshowModal(). The code tries to replicate the original functionality as closely as possible while leveraging the nativeAPI.
Key Points of This Approach:
Native Modal Behavior:Usingdialog.showModal()automatically displays the dialog as a modal, preventing interaction with elements outside of it.
Focus Management:automatically handles focus when opened withshowModal().
Escape Key Handling:The dialog can be closed by the user pressing Esc by default. If we need a custom behavior, we can intercept thecancelevent or thecloseevent.
Return Values:We can usedialog.close(value)to set areturnValuethat helps differentiate how the dialog was closed.
Simplified Code:Usingreduces the need for a custom overlay and manual focus trapping.
Native Modal Behavior:Usingdialog.showModal()automatically displays the dialog as a modal, preventing interaction with elements outside of it.
Focus Management:automatically handles focus when opened withshowModal().
Escape Key Handling:The dialog can be closed by the user pressing Esc by default. If we need a custom behavior, we can intercept thecancelevent or thecloseevent.
Return Values:We can usedialog.close(value)to set areturnValuethat helps differentiate how the dialog was closed.
Simplified Code:Usingreduces the need for a custom overlay and manual focus trapping.
const form = document.createElement("form");
form.method = "dialog"; // Allows form to close the dialog on submission.
const msg = document.createElement("div");
applyStyles(msg, messageStyle);
msg.textContent = message;
form.appendChild(msg);
dialog.appendChild(form);
return { dialog, form };
}
function createButton(label, value, customStyles = {}) {
const btn = document.createElement("button");
applyStyles(btn, buttonStyle);
applyStyles(btn, customStyles);
btn.type = "submit";
btn.value = value; // form submission will set dialog.returnValue to this
btn.textContent = label;
return btn;
}
async function alert(message) {
return new Promise((resolve) => {
const { dialog, form } = createDialog(message);
Creates aElement:Instead of manually creating an overlay and a container, it uses the nativeelement.
CallsshowModal()to Display the Dialog:This makes the dialog modal and handles background elements' interactivity.
Usesform.method = "dialog":Submitting the form (OKorCancelbuttons) automatically closes the dialog and setsdialog.returnValueto the button’svalue.
Oncloseevent:Resolves the promise based on thedialog.returnValue.Foralert(), there is only anokbutton, so no confusion.Forconfirm(),okreturnValue istrue,cancelisfalse, and ESC results in an empty string, treated ascancel(false).Forprompt(),okreturns the input’s value,cancelor ESC returnsnull.
(), there is only anokbutton, so no confusion.
Forconfirm(),okreturnValue istrue,cancelisfalse, and ESC results in an empty string, treated ascancel(false).
Forprompt(),okreturns the input’s value,cancelor ESC returnsnull.
Styling and Focus:Styles are applied similarly to the original code. The dialog natively handles focus, but we explicitly focus theOKbutton orinputfor convenience.
Creates aElement:Instead of manually creating an overlay and a container, it uses the nativeelement.
CallsshowModal()to Display the Dialog:This makes the dialog modal and handles background elements' interactivity.
Usesform.method = "dialog":Submitting the form (OKorCancelbuttons) automatically closes the dialog and setsdialog.returnValueto the button’svalue.
Oncloseevent:Resolves the promise based on turnValue.
(), there is only anokbutton, so no confusion.
Forconfirm(),okreturnValue istrue,cancelisfalse, and ESC results in an empty string, treated ascancel(false).
Forprompt(),okreturns the input’s value,cancelor ESC returnsnull.
(), there is only anokbutton, so no confusion.
Forconfirm(),okreturnValue istrue,cancelisfalse, and ESC results in an empty string, treated ascancel(false).
Forprompt(),okreturns the input’s value,cancelor ESC returnsnull.
Styling and Focus:Styles are applied similarly to the original code. The dialog natively handles focus, but we explicitly focus theOKbutton orinputfor convenience.
This approach relies fully onandshowModal(), significantly reducing the complexity required for focus management and escape key handling.
“Suggestions for improving this code - same exact functionality const Prompts = (function….” Conversation with o1, from the ShareChat — Chatbot Conversations in the Wild dataset. The Chat Archive, 2026. https://thechatarchive.com/c/01m84tn8swg7h26e2sh19wkt34