Explain Codes LogoExplain Codes Logo

How to create a dialog with “Ok” and “Cancel” options

javascript
custom-dialogs
accessibility
event-listeners
Anton ShumikhinbyAnton Shumikhin·Dec 23, 2024
TLDR

No need to run a marathon when you can take a shortcut, use the confirm() function for an 'out-of-the-box' dialog with "Ok" and "Cancel" buttons. Execute the aftermath like this:

if (confirm("Ready to run into the rabbit hole?")) { // Down the rabbit hole we go! } else { // Phew! Dodged the bullet. }

confirm() behaves like a loyal pet giving back true if Ok is clicked, a grumpy false if Cancel.

Custom dialog – Sky's the limit!

confirm() though handy, is old-school and offers about as much customization as a brick, i.e., none. For a design that's in-sync with your UI, create a custom modal with HTML, CSS, and JavaScript. Although the pattern remains the same, the presentation gets a fancy overhaul.

Accessibility – Leave no user behind!

While crafting your lustrous custom dialog, don't forget the keyboard warriors, bake in accessibility. Use role="dialog", ensnare focus within the modal to prevent accidental slippages onto the background elements.

The Nitty-Gritty - Delving Deeper with Custom Dialogs

Code hygiene – Untangle the mess!

Let's ditch the janitor's work of maintaining onclick attributes, embrace programmatic event listeners instead. Use data attributes for dynamic confirm messages, keep your JS in JS, and your HTML in HTML – your future self will thank you.

Dress right - Styling your custom dialogs

Sprinkle some stardust, use CSS to grab attention and enhance the visual appeal of custom confirm dialogs. Throw some transitions for a smoother waltz, and don't forget the dance of media queries for responsive choreography.

More than meets the eye - Dealing with complex scenarios

Forms, sneaky as they are, if "Cancel" prevails, prevent their sneaky submission by returning false from your handler. And if you're partying with dynamic elements or SPAs(single-page applications), send an invite to jQuery's .on() for a hassle-free bash.

Expert Level – Mastering Dialogs

Proper Planning - Keep things tidy!

Your future self likes coffee, but hates debugging, keep your code modular for easy maintenance. Ensure a separate function handles the aftermath of each user choice, especially relevant for complex interactions.

Living the SPA life

In the land of SPAs, there's an abundance of user interaction and thus more state management. A framework like React or Vue could be your knight in shining armor managing dialog states, saving you from the dragon of complexity.

User-driven Customization

When your users are at the wheel, they'll need extra details for making a decision. Leave placeholders in your dialogs for warnings, or even a compass (additional instructions).