๐ค Popups & Window Controls in JavaScript
JavaScript provides several built-in methods to open dialog boxes and control browser windows. These can be useful for alerts, prompts, confirmations, or opening new windows.
๐ 1. Alert, Prompt, and Confirm
// Simple alert box
alert("This is an alert!");
// Prompt for user input
const name = prompt("What's your name?");
console.log("User entered:", name);
// Confirmation box
const confirmed = confirm("Are you sure you want to continue?");
console.log("User clicked:", confirmed);
alert()
: Shows a message box with OKprompt()
: Asks user for inputconfirm()
: Asks for Yes/No confirmation
๐ช 2. Opening New Windows
// Open a new tab or window
const newWin = window.open(
"https://example.com",
"_blank",
"width=600,height=400,resizable=yes"
);
window.open()
: Opens a new browser window or tab- Arguments:
URL
,target
,features
- Common features:
width
,height
,resizable
,scrollbars
๐งน 3. Closing Windows
If your script opened a window using window.open()
, it can also close it:
// Close the window (only if script opened it)
newWin.close();
Note: Most modern browsers block popups unless triggered by direct user actions (like clicking a button).
๐ซ 4. Popup Blocking
- Browsers often block popups opened automatically without user interaction.
- Always tie popups to click events or user triggers.
- Use responsibly to avoid bad user experience.
โ ๏ธ Tip: Avoid using popups excessively. Use modal dialogs (via HTML/CSS/JS) for better UX.