jQuery click event does not work when fullscreen iframe in the background?

733 Views Asked by At

jQuery click event won't fire when there is a fullscreen iframe in the background :

JS :

$( document ).ready(function() {

    $(document).click(function(){
        if ($(this).find('.overlay').is(':visible')) {
            $('.overlay').hide();
        } else {
            $('.overlay').show();
        }
    });

});

HTML :

<body>

    <div class="overlay">Overlay</div>

    <iframe src="iframe.html" name="frame" style="position:fixed; top:0; left:0; right:0; bottom:0; width:100%; height:100%"></iframe>

</body>

CSS :

body {
  margin: 0;
}

.overlay {
  width:200px;
  height:200px;
  background-color: green;
  position:fixed;
  top:0;
  left:0;
  z-index: 10;
}

I want to hide/ toggle the green box when then the click is occurred outside the box.

Any ideas how can I fix this?

2

There are 2 best solutions below

3
Shikkediel On BEST ANSWER

To access an iframe, .contents() can be used :

Demo

$(document).ready(function() {

    $('[name="frame"]').on('load', function() {

        $(this).contents().click(function() {

        if ($('.overlay').is(':visible')) $('.overlay').hide();
        else $('.overlay').show();
        });
    });
});

The .contents() method can also be used to get the content document of an iframe, if the iframe is on the same domain as the main page.

https://api.jquery.com/contents/

If the content is on another domain, the only option would probably be to put an element on top of it.

Edit - code adjusted, it's important to wait for the iframe to load before applying the event handler...

1
Renan Bardy On

If the event is about that div (overlay) you should add listenner in overlay class with jquery, try these example and tell about the results

$(".overlay").click(function (){
 $(this).slideToggle();
}):

or

$(".overlay").click(function (){
 if($(this).hassClass('hide')){
  return $(this).removeClass('hide');
 }
 return $(this).addClass('hide');
});

css

 .hide{
    display:none;
    }