I\'m trying to build a popup that can be closed from anywhere.
On the Mainpage you have the option to open it. At any point while browsing the mainpage the user shall be
If you just need the popup to be closed automatically when you leave the main page (as suggested in a comment), you just need to do the following:
$(window).unload(closepopup);
If you are trying to close it from an iframe...
top.my_window.close();
I believe you need to go out a level since that variable is set on the parent window. Not in the iframe.
There are three solutions I propose depending on what the problem actually is.
If you need to close the popup from page B when it was opened from page A the following code will allow you to obtain a reference to the popup from page B and close it. Reference: Find window previously opened by window.open
PageA.html
<script>
function popuponclick()
{
my_window = window.open("http://google.com", "mywindow","status=1,width=350,height=150");
}
function closepopup()
{
my_window.close ();
}
</script>
<a href="javascript:popuponclick()">Open window...</a></br>
<a href="PageB.html">Go to Page B</a>
</body>
</html>
PageB.html
<html>
<body>
<script>
function closepopup()
{
var popupPlayer= window.open('', 'mywindow', 'status=1,width=350,height=150') ;
popupPlayer.focus();
popupPlayer.close();
}
</script>
<a href="javascript:closepopup()">Close window...</a></br>
</body>
</html>
A global reference to my_window is needed so you would need to change the code like this:
var my_window; //global reference here
function popuponclick()
{
my_window = window.open("", "mywindow","status=1,width=350,height=150");
}
function closepopup()
{
my_window.close ();
}
You separate your page into 1 frames (one which is 100%) and another that is 0%.
You add the window open/close code in the parent frame. Than you call the window control code via cross frame javascript commands.
Frames HTML Containing Javascript
<html>
<head>
<title>My example</title>
<script>
var my_window;
function popuponclick()
{
my_window = window.open("", "mywindow","status=1,width=350,height=150");
}
function closepopup()
{
my_window.close ();
}
</script>
</head>
<frameset cols="100%,0%">
<frame src="frame.html"/>
<frame/>
</frameset>
</html>
Internal Frame (frame.html) - calling parent Javascript
<html>
<body>
<a href="javascript:parent.popuponclick()"> Open Window </a><br/>
<a href="javascript:parent.closepopup()"> Close Window </a><br/>
<a href="javascript:location.href=location.href"> Refresh Frame (and try again)</a><br/>
</body>
</html>