- 1 1. Introduction: What Is the confirm Method?
- 2 2. Basic Syntax and Usage of the confirm Method
- 3 3. Example ①: Confirmation Dialog on Form Submission
- 4 4. Example ②: Confirmation Dialog on Link Click
- 5 5. Use Cases and Precautions for the confirm Method
- 6 6. How to Implement Custom Dialogs (Advanced)
- 7 7. Frequently Asked Questions (FAQ): Solving Common confirm Method Issues
- 7.1 Q1. Why is the confirm method not working?
- 7.2 Q2. Can I change the design of the confirm dialog?
- 7.3 Q3. Why does the confirm method behave differently on mobile devices?
- 7.4 Q4. Why does Japanese text become garbled in confirm dialogs?
- 7.5 Q5. Can I implement similar functionality without using confirm?
- 7.6 Q6. How can I use the confirm result outside a function?
- 7.7 Summary
- 8 8. Conclusion: Effective Use of the confirm Method
1. Introduction: What Is the confirm Method?
JavaScript provides various features for interacting with users. Among them, the confirm method is a convenient feature that displays a confirmation dialog to prompt the user to make a choice.
This method presents the user with “OK” or “Cancel” options and is used when you want to execute different logic depending on the user’s selection. For example, it is useful when you need the user to confirm an important action such as submitting a form or deleting data.
Main Use Cases of the confirm Method
- Perform a final confirmation before submitting a form.
- Show a warning before deleting files or data.
- Display a dialog to confirm page navigation or cancel an operation.
Differences Between confirm and Other Dialogs
JavaScript has the following three methods for interacting with users.
- alert method: Used to simply display a message. No user input is required.
alert("Warning: Your changes will not be saved!");- prompt method: Used to receive input from the user.
let name = prompt("Please enter your name:", "Guest");- confirm method: Prompts the user to choose “OK” or “Cancel.”
let result = confirm("Are you sure you want to delete this?");The confirm method is ideal when you want to confirm the user’s explicit intent.
Basic Behavior of the confirm Method
The confirm method returns true or false depending on the user’s choice.
- If the user clicks “OK”: true
- If the user clicks “Cancel”: false
With this simple mechanism, you can easily implement conditional branching and error handling.
Common Real-World Scenarios
The confirm method is helpful in situations such as:
- Confirming “Are you sure you want to delete this?” before a user deletes an important file.
- Asking “Do you want to submit this?” before submitting a form.
- Notifying “You have unsaved changes. Do you want to leave this page?” before navigating away.
Summary
The confirm method is a very useful feature for presenting choices to users and confirming important actions. As one of JavaScript’s basic features, it is widely used across many websites and applications. In the next section, we will explain in detail how to use this method.

2. Basic Syntax and Usage of the confirm Method
The confirm method is a simple and convenient feature in JavaScript for confirming a user’s intent. In this section, we will explain the basic syntax and how to use it in detail.
Basic Syntax
let result = confirm(message);Argument
- message (required): Specifies the text to display in the dialog.
Return Value
- true: Returned when the “OK” button is pressed.
- false: Returned when the “Cancel” button is pressed.
Example 1: Displaying a Basic Confirmation Dialog
Below is a simple example of using the confirm method to confirm a deletion.
let result = confirm("Are you sure you want to delete this?");
if (result) {
alert("Deleted.");
} else {
alert("Canceled.");
}Example 2: Confirmation on Form Submission
Here is an example that shows a confirmation dialog before submitting a form to confirm the user’s intent.
HTML code:
<form id="myForm" action="/submit" method="post">
<button type="submit">Submit</button>
</form>JavaScript code:
document.getElementById("myForm").addEventListener("submit", function(event) {
let result = confirm("Are you sure you want to submit?");
if (!result) {
event.preventDefault(); // Cancel form submission
}
});Example 3: Confirmation When Clicking a Link
Here is an example that confirms navigation when the user clicks a link.
HTML code:
<a href="https://example.com" id="myLink">Open link</a>JavaScript code:
document.getElementById("myLink").addEventListener("click", function(event) {
let result = confirm("Do you want to leave this page?");
if (!result) {
event.preventDefault(); // Cancel navigation
}
});Important Notes for Use
- Avoid excessive use The confirm method can interrupt the user’s flow, so using it too often may reduce UX (user experience). Keep it to the minimum necessary.
- Consider mobile usability On mobile devices, the dialog area is smaller, so avoid overly long messages and keep them concise.
- Consider custom dialogs If you need to customize the design, consider using a custom dialog built with HTML, CSS, and JavaScript rather than the confirm method. We will cover details later in this article.
Summary
The confirm method provides a simple way to get user confirmation in JavaScript. In this section, we covered everything from the basic syntax to practical examples.
3. Example ①: Confirmation Dialog on Form Submission
Form submission is treated as an important action because users may unintentionally submit incorrect information. In this section, we explain how to show a confirmation dialog before submitting a form to ensure the user’s action is intentional.
Basic Confirmation Dialog for Form Submission
Below is a simple example that asks the user, “Do you want to submit with this content?” before sending the form.
HTML code:
<form id="contactForm" action="/submit" method="post">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>
<button type="submit">Submit</button>
</form>JavaScript code:
document.getElementById("contactForm").addEventListener("submit", function(event) {
let result = confirm("Do you want to submit with this content?");
if (!result) {
event.preventDefault(); // Cancel submission
}
});Add a Feature to Confirm the Entered Content
Below is an example that shows a dialog confirming what the user entered in the form.
HTML code:
<form id="feedbackForm" action="/submit" method="post">
<label for="email">Email address:</label>
<input type="email" id="email" name="email" required>
<label for="message">Message:</label>
<textarea id="message" name="message" required></textarea>
<button type="submit">Submit</button>
</form>JavaScript code:
document.getElementById("feedbackForm").addEventListener("submit", function(event) {
let email = document.getElementById("email").value;
let message = document.getElementById("message").value;
let result = confirm(
"Do you want to submit with the following content?\n\n" +
"Email: " + email + "\n" +
"Message: " + message
);
if (!result) {
event.preventDefault(); // Cancel submission
}
});Error Checking and Validation
You can also combine confirmation with validation as shown below.
JavaScript code:
document.getElementById("contactForm").addEventListener("submit", function(event) {
let name = document.getElementById("name").value.trim();
if (name === "") {
alert("Please enter your name!");
event.preventDefault(); // Cancel submission
return;
}
let result = confirm("Do you want to submit with this content?");
if (!result) {
event.preventDefault(); // Cancel submission
}
});Notes for Mobile Support
- Keep messages concise: Since screen space is limited on mobile, keep dialog messages short and clear.
- Minimize user actions: Show the confirmation only once before submission, and design it so it does not appear multiple times.
Summary
A confirmation dialog for form submission is an important feature that prevents mistakes and gives users peace of mind.
In this section, we introduced basic confirmation logic using the confirm method, how to confirm entered content, and advanced examples combined with validation.

4. Example ②: Confirmation Dialog on Link Click
To prevent users from accidentally navigating away when clicking a link on a web page, you can use the confirm method to display a confirmation dialog. In this section, we explain concrete implementation methods.
Basic Link-Click Confirmation Dialog
Below is a basic example that shows a confirmation dialog asking, “Do you really want to leave this page?” when clicking a link.
HTML code:
<a href="https://example.com" id="externalLink">Go to external site</a>JavaScript code:
document.getElementById("externalLink").addEventListener("click", function(event) {
let result = confirm("Do you want to leave this page? Unsaved changes may be lost.");
if (!result) {
event.preventDefault(); // Cancel link navigation
}
});Handling Dynamically Generated Links
You can set a confirmation dialog for links that are generated dynamically as well.
HTML code:
<div id="linkContainer">
<a href="https://example.com/page1">Link 1</a>
<a href="https://example.com/page2">Link 2</a>
</div>JavaScript code:
document.getElementById("linkContainer").addEventListener("click", function(event) {
if (event.target.tagName === "A") {
let result = confirm("Do you want to leave this page?");
if (!result) {
event.preventDefault(); // Cancel navigation
}
}
});Separate Handling for Internal and External Links
If you want to show different dialogs for external and internal links, you can branch the logic by checking the link URL (or class).
HTML code:
<a href="/internal-page.html" class="internal">Internal link</a>
<a href="https://example.com" class="external">External link</a>JavaScript code:
document.querySelectorAll("a").forEach(link => {
link.addEventListener("click", function(event) {
if (link.classList.contains("external")) {
let result = confirm("You are about to leave for an external site. Continue?");
if (!result) {
event.preventDefault();
}
} else if (link.classList.contains("internal")) {
let result = confirm("Do you want to leave this page? Unsaved changes may be lost.");
if (!result) {
event.preventDefault();
}
}
});
});Notes for Mobile Support
- Use short messages: Since screen space is limited on mobile, keep dialog messages short and clear.
- Add mis-tap prevention measures: For mobile users, consider adding features to prevent accidental clicks, such as double-tap prevention or swipe-based mis-click prevention.
Advanced: Apply to Multiple Links at Once
If you want to apply a confirmation dialog to all links, you can create generic code like the following.
JavaScript code:
document.querySelectorAll("a").forEach(link => {
link.addEventListener("click", function(event) {
let result = confirm("Do you want to open this link?");
if (!result) {
event.preventDefault(); // Cancel navigation
}
});
});Summary
In this section, we explained how to use the confirm method to display a confirmation dialog when clicking links.
- We introduced various implementation patterns, from basic examples to handling dynamic links, and even branching behavior for external vs. internal links.
- The confirm method is highly effective for preventing mistakes and improving user experience.
5. Use Cases and Precautions for the confirm Method
The confirm method is widely used to prompt users to confirm important actions. In this section, we explain common use cases and important points to keep in mind during implementation.
Common Use Cases
- Confirming Data Deletion Accidental data deletion can cause irreversible problems. Using the confirm method allows users to reconfirm their intent and helps prevent such accidents. Example:
let result = confirm("Are you sure you want to delete this data?");
if (result) {
alert("The data has been deleted.");
} else {
alert("Deletion was canceled.");
}- Final Confirmation Before Form Submission This helps users recheck the submitted content and prevent input mistakes. Refer to the examples in “3. Example ①: Confirmation Dialog on Form Submission.”
- Warnings on Page Navigation or Exit Display a warning when users attempt to leave a page with unsaved data or during an important process. Example:
window.addEventListener("beforeunload", function(event) {
event.preventDefault();
event.returnValue = "Your changes have not been saved. Do you want to leave this page?";
});- Permission Confirmation for Actions Useful for asking confirmation before executing specific features (e.g., printing or exporting). Example:
let result = confirm("Do you want to print this report?");
if (result) {
window.print();
}Important Implementation Considerations
1. Avoid Excessive Use
Although convenient, excessive use of the confirm method can stress users. If dialogs appear too frequently, users may habitually click “OK” without reading.
Countermeasures:
- Use it only for truly important actions.
- Consider custom dialogs for repeated interactions.
2. Consider Usability on Mobile Devices
On mobile devices, confirm dialogs may be hard to read due to limited screen space, and accidental taps are more likely.
Countermeasures:
- Keep messages concise.
- Implement custom dialogs with larger, touch-friendly buttons.
3. Limited Customization
The confirm method uses a browser-native dialog, so you cannot customize its design or layout. For branding-focused sites, custom dialogs are recommended.
Countermeasures:
- Create your own modal windows using HTML + CSS + JavaScript.
- Use existing libraries (e.g., SweetAlert2) for stylish dialogs.
4. Browser-Dependent Behavior
While supported by all modern browsers, behavior may vary in older browsers, and dialogs may be blocked depending on browser settings.
Countermeasures:
- Prepare fallback options such as custom dialogs.
- Perform cross-browser testing to ensure compatibility.
5. Security Considerations
The confirm method is not a security feature. Malicious users may bypass it by manipulating scripts.
Countermeasures:
- Combine client-side confirmation with server-side validation for stronger security.
Summary
The confirm method is a powerful tool for prompting user confirmation before executing important actions. However, excessive use, mobile usability issues, and limited customization must be considered.
Key Points:
- Clearly define use cases and keep usage to a minimum.
- Prepare concise messages for mobile users.
- Use custom dialogs when design flexibility is required.
- Combine with server-side validation for better security.

6. How to Implement Custom Dialogs (Advanced)
While the confirm method is easy to use, it has limitations in terms of design customization and layout control. To address this, this section explains how to create more flexible and visually appealing custom dialogs using HTML, CSS, and JavaScript.
Advantages of Custom Dialogs
- Design Flexibility You can customize colors and fonts to match your brand identity.
- Support for Complex Interactions You can add text inputs or multiple buttons that are not possible with the standard confirm method.
- Easy Mobile Optimization You can create responsive, mobile-friendly layouts.
Basic Custom Dialog Implementation
Below is an example of a simple custom confirmation dialog.
HTML Code:
<div id="customDialog" class="dialog-overlay" style="display: none;">
<div class="dialog-box">
<p id="dialogMessage">Are you sure you want to delete this?</p>
<div class="dialog-buttons">
<button id="dialogYes">Yes</button>
<button id="dialogNo">No</button>
</div>
</div>
</div>
<button id="deleteButton">Delete</button>CSS Code:
.dialog-overlay {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.6);
display: flex;
align-items: center;
justify-content: center;
z-index: 9999;
}
.dialog-box {
background: white;
padding: 20px;
border-radius: 8px;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
width: 300px;
text-align: center;
}
.dialog-buttons {
margin-top: 20px;
display: flex;
justify-content: center;
gap: 10px;
}
.dialog-buttons button {
padding: 10px 20px;
border: none;
border-radius: 4px;
cursor: pointer;
}
#dialogYes {
background: #007BFF;
color: white;
}
#dialogNo {
background: #6c757d;
color: white;
}JavaScript Code:
document.getElementById("deleteButton").addEventListener("click", function () {
showDialog("Are you sure you want to delete this?", function (confirmed) {
if (confirmed) {
alert("The data has been deleted.");
} else {
alert("Deletion was canceled.");
}
});
});
function showDialog(message, callback) {
const dialog = document.getElementById("customDialog");
const dialogMessage = document.getElementById("dialogMessage");
const yesButton = document.getElementById("dialogYes");
const noButton = document.getElementById("dialogNo");
dialogMessage.textContent = message;
dialog.style.display = "flex";
yesButton.onclick = function () {
dialog.style.display = "none";
callback(true);
};
noButton.onclick = function () {
dialog.style.display = "none";
callback(false);
};
}Extending Custom Dialogs
- Add Text Input Add input fields like the prompt method to collect user input.
- Add Animations Use CSS animations to add fade-in or slide effects when showing or hiding dialogs.
- Use Libraries If implementing from scratch is time-consuming, consider using libraries:
- SweetAlert2 A modern and stylish dialog library. Official website
- Bootstrap Modal Dialog functionality provided by the Bootstrap framework.
Mobile Optimization Tips
- Apply Responsive Design Adjust dialog size and positioning based on screen size.
- Design Touch-Friendly Buttons Increase button size to prevent accidental taps on touch devices.
Summary
Custom dialogs provide flexible designs and features that cannot be achieved with the confirm method.
Key Points:
- Use custom dialogs when you need design or functional flexibility.
- Combine HTML, CSS, and JavaScript to create fully customizable dialogs.
- Leverage libraries to improve development efficiency.

7. Frequently Asked Questions (FAQ): Solving Common confirm Method Issues
In this section, we address common questions and issues readers often have about the confirm method, along with practical solutions.
Q1. Why is the confirm method not working?
Cause 1: JavaScript errors
If there are syntax errors or typos in your code, the confirm method will not work correctly.
Solution:
Check error messages in the browser’s developer tools (open with F12) and fix the code.
Example:
let result = confirm("Do you want to perform this action?");Q2. Can I change the design of the confirm dialog?
Answer: No.
The confirm method uses a browser-native dialog, so you cannot customize its style or layout.
Solution: Create a custom dialog
Refer to the examples in “6. How to Implement Custom Dialogs (Advanced)” to build a dialog that matches your design.
Q3. Why does the confirm method behave differently on mobile devices?
Cause: Browser and OS-dependent behavior
On mobile browsers, confirm dialogs may look or behave differently from desktop versions.
Solution:
- Keep messages short and concise.
- Use custom dialogs with touch-friendly buttons.
Q4. Why does Japanese text become garbled in confirm dialogs?
Cause: Character encoding issues
If the HTML file or server is not configured with the correct character encoding, text may appear garbled.
Solution:
Set the character encoding to UTF-8 by adding the following to your HTML head:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>Q5. Can I implement similar functionality without using confirm?
Answer: Yes.
Two common alternatives are:
- Custom dialogs (HTML + CSS + JavaScript)
- Using external libraries
- SweetAlert2 example:
Swal.fire({
title: "Are you sure you want to delete this?",
text: "This action cannot be undone.",
icon: "warning",
showCancelButton: true,
confirmButtonText: "Yes",
cancelButtonText: "No"
}).then((result) => {
if (result.isConfirmed) {
alert("Deleted!");
}
});Q6. How can I use the confirm result outside a function?
Answer: Use callbacks or Promises.
Example 1: Using a callback
function confirmAction(message, callback) {
let result = confirm(message);
callback(result);
}
confirmAction("Proceed?", function(response) {
if (response) {
alert("Executed!");
} else {
alert("Canceled!");
}
});Example 2: Using a Promise
function confirmAsync(message) {
return new Promise((resolve) => {
let result = confirm(message);
resolve(result);
});
}
confirmAsync("Proceed?").then((confirmed) => {
if (confirmed) {
alert("Executed!");
} else {
alert("Canceled!");
}
});Summary
This section covered common questions and solutions related to the confirm method.
Key Points:
- If customization is required, use custom dialogs or external libraries.
- When it does not work, check for JavaScript errors and event listener issues.
- Proper mobile support and character encoding improve user experience.

8. Conclusion: Effective Use of the confirm Method
In this article, we explored the JavaScript confirm method in detail—from basic usage to practical examples, customization techniques, and answers to common questions. In this final section, we summarize key takeaways for effective use.
1. Core Role of the confirm Method
The confirm method provides a simple dialog that prompts users to choose “OK” or “Cancel.”
Main purposes:
- Confirming important actions (data deletion, submissions)
- Displaying warnings during page navigation
- Performing final checks to prevent mistakes
2. Practical Examples and Advanced Usage
- Form submission confirmation
- Link click confirmation
- Advanced usage with custom dialogs
3. Important Points When Using confirm
- Avoid excessive use to preserve user experience.
- Consider mobile usability with concise messages.
- Use custom dialogs or libraries when design flexibility is required.
- Combine with server-side validation for better security.
4. Choosing Between confirm and Custom Dialogs
Use confirm when:
- You need a quick and simple confirmation.
- No special design customization is required.
Use custom dialogs when:
- Branding and design flexibility are important.
- Advanced interactions (inputs, multiple options) are needed.
Final Summary
The confirm method is a fundamental element of user interaction in JavaScript. Its simplicity makes it suitable for beginners and professionals alike.
Key Takeaways:
- Use confirmation dialogs thoughtfully for important actions.
- Enhance functionality and design with custom dialogs when necessary.
- Design confirmation flows that do not disrupt the user experience.



