Click here to open the preserved 400 × 200 sample popup.
window.open() should be called directly from a user action such as a click, otherwise browsers may block it. The returned value can also be null when the popup is blocked, so the example checks for that condition.
<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>JavaScript Popup</title></head><body>
<a href="#" id="popup-link">Generate popup</a><p id="popup-status" aria-live="polite"></p><script>function popup(width, height) {
const left=Math.max(0, Math.round((window.screen.availWidth-width)/2));
const top=Math.max(0, Math.round((window.screen.availHeight-height)/2));
const features=`popup=yes,resizable=yes,scrollbars=yes,width=${width},height=${height},left=${left},top=${top}`;
const popWin=window.open('', 'new_window', features);
if (!popWin) {
document.getElementById('popup-status').textContent='The popup was blocked. Allow popups for this site and try again.';
return;
}
popWin.document.title='Test Popup';
popWin.document.body.replaceChildren();
const wrapper=popWin.document.createElement('div');
wrapper.style.textAlign='center';
const heading=popWin.document.createElement('strong');
heading.textContent='This is a test popup window';
const paragraph=popWin.document.createElement('p');
paragraph.textContent='Content goes here';
wrapper.append(heading, paragraph);
popWin.document.body.append(wrapper);
popWin.focus();
}
document.getElementById('popup-link').addEventListener('click',(event)=>{
event.preventDefault();
popup(400,200);
});</script></body></html>
The original code centered the popup by calculating screen coordinates and wrote several lines into the new window with repeated document.write() calls. The updated example keeps the same centered popup/content facility but builds the content with DOM methods instead.
Window prompt window for input data →
← Window Object Bookmark a page → Redirect Page →
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.
| varatharajan | 27-01-2014 |
| hi, i want to popup menu without minimize,maximum button.... only its will be have close option...pls reply soon...I'm waiting for your reply..... | |
| smo | 28-01-2014 |
| You can display layers with one option to close window. Read this hide layer | |