Popups and Window Methods in JavaScript
JavaScript provides several methods to create popups and interact with browser windows. These are mainly used for displaying alerts, user confirmations, and opening new browser windows.
🔹 1. Alert, Confirm, and Prompt
JavaScript has three built-in popup boxes:
✅ alert()
- Simple Message Popup
Displays a message to the user.
✔ Used for notifications or warnings.
✅ confirm()
- Yes/No Popup
Displays a message with OK and Cancel buttons.
✔ Used to ask for confirmation before performing an action.
✅ prompt()
- User Input Popup
Asks the user for input.
✔ If the user cancels, prompt()
returns null
.
🔹 2. Opening a New Window (window.open()
)
You can open a new browser window using window.open()
.
✔ Parameters:
"https://www.google.com"
→ URL to open"_blank"
→ Opens in a new tab (Use"_self"
to open in the same tab)"width=500,height=500"
→ Set window size
🔹 3. Closing a Window (window.close()
)
You can close a window using window.close()
, but only if it was opened with window.open()
.
⚠ Note: Browsers may block window.close()
unless triggered by user action (like a button click).
🔹 4. Moving and Resizing a Window
You can control the position and size of a window (only for popups, not the main window).
✅ window.resizeTo(width, height)
Resizes the popup window.
✅ window.moveTo(x, y)
Moves the popup to a specific screen position.
✔ Useful for positioning popups dynamically.
🔹 5. Window Properties (window.innerWidth
, window.innerHeight
)
You can get the current window size using:
🔹 6. Prevent Popups from Being Blocked
Modern browsers block popups unless triggered by a user action.
✅ Solution: Open popups inside a button click event.
✔ Avoid opening popups automatically when the page loads.
🔹 7. Example: Open, Resize, and Close a Window
✔ This lets the user open, resize, and close a popup window dynamically.
🔹 Summary
✔ alert()
, confirm()
, and prompt()
display popups.
✔ window.open()
creates a new browser window.
✔ window.close()
closes a window (if user-initiated).
✔ resizeTo()
and moveTo()
adjust the window's size and position.
✔ Browsers block auto popups, so trigger them inside user actions.
🚀 Use popups wisely to improve user interaction!