0

How can i close an iframe when I click outside ?

This is how I'm creating the iframe on the parent

    <script type="text/javascript">

function checkip() {
    var iframe = document.createElement("iframe");     
    iframe.id="capa";
    iframe.name="test1";
 iframe.src = "iframe2.html";
 iframe.width = "200";
 iframe.height = "200";
 iframe.frameBorder = "1";
 iframe.scrolling = "no"; 
 //document.body.replaceChild(iframe, lastElementChild);
 document.body.appendChild(iframe);

}
    </script>

This is how im closing the iframe.

   function _ocultarIframe(){

 // document.getElementById('capa').style.display = 'none';
 var elem = document.getElementById("capa");
   elem.parentNode.removeChild(elem);

  }
    </script>
Alex83690
  • 758
  • 9
  • 30
  • Sorry is when i click out of the iframe – Antonio Rivas Sep 11 '18 at 22:17
  • Hi, I think that your question is a possible duplicate of [How do I detect a click outside an element?](https://stackoverflow.com/questions/152975/how-do-i-detect-a-click-outside-an-element) – Alex83690 Sep 12 '18 at 07:05

3 Answers3

0

If you don't want to use jQuery, ignore this answer.But it will be easier if you user jQuery.

jQuery:

$(document).on("click", function(e) {
    //If you click on document it will close the iframe.
    $("iframe").addClass("hide");
});

$("#capa").on("click", function(e) {
    //But if you click on iframe, the default behaviour of closing of iframe is stopped.
    e.stopPropagation();
});

CSS:

.hide {
    display:none;
}
Nandan Bhat
  • 1,573
  • 2
  • 9
  • 21
0

Check if your iframe is target to click event using Jquery is() and e.target which is A reference to the object that dispatched the event.

$("html").click(function(e) {
var iframe = $('#capa');
if (!iframe.is(e.target))     {
    _ocultarIframe();
    }
  });
Osama
  • 2,912
  • 1
  • 12
  • 15
0

You could be doing something like this.

In sense of "closing" Iframe im not sure if you meant to hide/remove/slide it away, but this would just toggle it's height.

document.addEventListener('click', function () {
  var iFrame = document.querySelector('#capa')
  iFrame.height = iFrame.height > 0 ? 0 : 200 // conditional height toggle
})
Jimi Pajala
  • 2,358
  • 11
  • 20