Module 3: Operators and User Interaction
Dialog Boxes: alert(), confirm(), prompt()
JavaScript provides built-in functions to create simple dialog boxes for user interaction. These are modal, meaning they block further interaction with the page until dismissed.
-
alert(message)
: Displays a message and an OK button.alert("Welcome to our website!");
-
confirm(message)
: Displays a message with an OK and a Cancel button. Returnstrue
if OK is clicked,false
if Cancel is clicked.let userConfirmed = confirm("Are you sure you want to proceed?"); if (userConfirmed) { console.log("User clicked OK."); } else { console.log("User clicked Cancel."); }
-
prompt(message, defaultValue)
: Displays a message, an input field, an OK button, and a Cancel button.- Returns the text entered by the user if OK is clicked.
- Returns
null
if Cancel is clicked or the dialog is closed. - The
defaultValue
is an optional string that will appear in the input field initially.
let userName = prompt("Please enter your name:", "Guest"); if (userName !== null && userName !== "") { console.log("Hello, " + userName + "!"); } else { console.log("User cancelled or entered no name."); }
Note: While these dialogs are easy to use, they are generally considered disruptive to the user experience in modern web design. For more sophisticated user interactions, custom HTML modals or UI library components are preferred.