Trigger on click anywhere in the document, even with an iframe?

So I am creating a widget that should "close" if the user clicks anywhere outside of it.

The obvious solution is to install a click handler on the document. This is fine, except that there are other parts of the application that use event.stopPropagation (). Therefore, we use the capture stage in our listener to get around this.

This works for everything, it seems, except for the iframe. I've made a simple jsfiddle to demonstrate what I'm talking about . Code Transcript:

var c = document.getElementById('clickme');
var s = document.getElementById('stop');
var t = document.getElementById('text');

document.addEventListener('click', function (event) {
  if (event.target !== c) {
    t.innerHTML += 'outside <br>';
  } else {
    t.innerHTML += 'inside <br>';
  }
}, true); //true to use capturing phase

s.addEventListener('click', function (event) {
  event.stopPropagation();
});

      

And setting:

<html>
<body>
  <p>Clicking anywhere but the button counts as an 'outside' click. However, clicks within the iframe do not trigger the event listener.</p>
  <div><button id="clickme">Click me!</button></div>
  <iframe>lalala</iframe>
  <div><button id="stop">Even Me, and I stopPropagation()</button></div>
  <div id="text"></div>
</body>
</html>

      

Is there a way to make this handler also trigger clicks inside / on the iframe? Also, at the time I attach the event listener, I won't be referring to the iframe, so a solution that doesn't require this would be better.

+3


source to share


1 answer


You can only detect a click event inside an iframe if it is on the same domain. See @ Tim Down's answer in JavaScript: link detection inside iframe

If the iframe is on a different domain, you can take advantage of the fact that when the iframe is clicked, a blur event will occur in the document. To do this, you need to set tabIndex

on the body element:

document.body.tabIndex= 0;

document.addEventListener('blur', function (event) {
  t.innerHTML += 'outside <br>';
}, true);

      



Note that multiple clicks inside the iframe will only fire one blur event.

Fiddle: http://jsfiddle.net/zrgrt9pf/13/

+2


source







All Articles