I have been using JavaScript popup windows, the windows were not saved as variables when I trigger them to open
Here is my code
function trig(){var pwin = window.open('https://stackoverflow.com/questions/68612238/popup-window-javascript','popUpWindow','height=500,width=400,left=100,top=100,resizable=yes,scrollbars=yes,toolbar=yes,status=yes');document.querySelector('body').setAttribute('onclick', 'pwin.close()')};
<div onclick="trig()">Click here</div>
Here is an external link to try it
after clicking the Click Here button it should show a window, but I found out it doesn't save it as a variable. and then after the user presses the <body> element the window should close
Couldn't debug out any issues.
2 Answers 2
pwin is not declared globally. You should instead be calling the close() method inside the function.
function trig() {
var pwin = window.open('https://stackoverflow.com/questions/68612238/popup-window-javascript', 'popUpWindow', 'height=500,width=400,left=100,top=100,resizable=yes,scrollbars=yes,toolbar=yes,status=yes');
document.querySelector('body').addEventListener('click', () => pwin.close());
};
It's closing immediately because when you click the 'Click here' button to open the window, the click event listener is added before the click event finishes firing, so it is immediately closed.
Instead, use setTimeout to add the event listener after, say, 50 milliseconds:
function trig() {
var pwin = window.open('https://stackoverflow.com/questions/68612238/popup-window-javascript', 'popUpWindow', 'height=500,width=400,left=100,top=100,resizable=yes,scrollbars=yes,toolbar=yes,status=yes');
setTimeout(()=>{document.querySelector('body').addEventListener('click', () => pwin.close());}, 50);
};
3 Comments
addEventListener() to set AFTER user clicks and the window opens.Looks like you need to declare a global variable, instead of a local variable
document.body.addEventListener('click', () => pwin.close());