0

I would like to close an iframe using a button that exists inside that iframe.

I have these two files, index.html and contents.html:

index.html

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style media="screen">
  a {
    postion: relative;
    top: 100px;
    left: 100px;
  }
</style>
  </head>
  <body>
<iframe id="outerIframe" src="./contents.html" width="1000px" height="1000px"></iframe>
<div class="behind">
  <a href="http://www.google.com">Mark Behind</a>
</div>
</body>
</html>

contents.html

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>

<style media="screen">
  .big-box {
    height: 500px;
    width: 500px;
    background-color: #666;
  }
</style>
</head>


 <body>
<div class="big-box">
  <button class="closer" type="button" name="button">Click to close</button>
</div>


<script type="text/javascript">
  var button = document.querySelector('.closer');
  button.addEventListener('click', function() {
    document.getElementById('outerIframe').style.display = "none";
  });
</script>
</body>
</html>

When I click the button, I get an error in the console that says "Cannot read property 'style' of null. I understand that means my attempt to get the iframe was not successful. How would I get the iframe this button resides in so that I can change the styles on it?

redeagle47
  • 1,355
  • 4
  • 14
  • 26

1 Answers1

1

Need to traverse up to parent window. An iframe has it's own window

Try

button.addEventListener('click', function() {
    window.parent.document.getElementById('outerIframe').style.display = "none";
});

DEMO

charlietfl
  • 170,828
  • 13
  • 121
  • 150