Links open and close via document.write

333 Views Asked by At

I'am trying to use window.close with the following link below

myWin.document.write("<a href='#' onclick=\"newMovie.window.close('http://www.imdb.com/title/tt2015381/','newMovie','height=600,width=600,left=400,top=100,scrollbars,status,resizable,dependent;')\"><b>Click Here to Close the Movie Window</b></a> <br><br>");

It isn't working. The idea is to be able to click and open one link which this works and click a second link to close the same window which isn't working.

Below are both links:

myWin.document.write("<div Id='box' style='text-align:center;");
myWin.document.write("<a href='#' onclick=\"window.open('http://www.imdb.com/title/tt2015381/','newMovie','height=600,width=600,left=400,top=100,scrollbars,status,resizable,dependent;')\"><b>Click Here to Access the Movie Window</b></a> <br><br>");
myWin.document.write("<a href='#' onclick=\"newMovie.window.close('http://www.imdb.com/title/tt2015381/','newMovie','height=600,width=600,left=400,top=100,scrollbars,status,resizable,dependent;')\"><b>Click Here to Close the Movie Window</b></a> <br><br>");

I'm missing something here? or is it easier to create a function() to close the link?

1

There are 1 best solutions below

0
iplus26 On

You've missed a few points:

  1. As bergi mentioned in the comments, naming the window doesn't create a variable. Use var newMovie = window.open(…) and newMovie.close() instead. And the variable newMovie is the reference to the window you create. Also pay attention to that, newMovie should be a global variable. Reference: window.open - MDN

  2. Be careful when you use document.write. The text you write is parsed into the document's structure model. In this case, you've missed a close syntax in your code:

    yours: myWin.document.write("<div Id='box' style='text-align:center;");

    correct: myWin.document.write("<div Id='box' style='text-align:center;'>");

You may not run the code directly, instead, copy all of it and run in your local .html file.

<!DOCTYPE html>
<html>
<head>
 <title>Test Page</title>
</head>
<body>
<script type="text/javascript">

 var newMovie = null; 

 document.write("<div id='box' style='text-align:center;'>");
 document.write("<a href='#' onclick='openNewWindow()'><b>Click Here to Access the Movie Window</b></a>");
 document.write("<a href='#' onclick='closeWindow()'><b>Click Here to Close the Movie Window</b></a>");

 function openNewWindow() {
  newMovie = window.open('http://www.imdb.com/title/tt2015381/','newMovie','height=600,width=600,left=400,top=100,scrollbars,status,resizable,dependent;');
 }

 function closeWindow() {
  newMovie.close();
 }
</script>
</body>
</html>