How ToJavaScriptMake Web StoriesQuiz GeneratorFAQ Schema GeneratorTable Maker3schools TranslateMore Tools..
Apu
Apu 11/20/2022

How to detect click inside iframe using JavaScript

How to detect click event inside iframe using JavaScript. Suppose you have five iframe elements on your webpage. You want to call another function whenever someone clicks on one of them.

How to detect click event inside iframe. #

The following example will display an alert message whenever you click inside the iframe.

Example : detect click event in iframe #
<iframe id="my-iframe" src="https://example.com" width="200" height="200"></iframe>
<script>
 window.focus();
 window.addEventListener("blur", () => {
  setTimeout(() => {
    if(document.activeElement.tagName === "IFRAME") {
      alert("Clicked");
    }
  });
 });
</script>
Try it Yourself »
  1. In the above example, we have an iframe element with an id my-iframe.
  2. Using JavaScript focus() method, we have focused the current web page. So that we can track cursor movement.
  3. We have used the addEventListener() method and track the blur event.
  4. Then we check if the currently focused element is an iframe. If it is an iframe element, we alert a message. We can also track a particular iframe.
    document.activeElement === document.querySelector('#my-iframe')

But the problem is, you can only detect the first click in the iframe. One can click multiple times on an iframe.

So for that problem, we have a trick. The below example will display an alert message whenever you click on the iframe.

Example : track the click event on iframe. #
<iframe id="my-iframe" src="/p/example.html" width="200" height="200"></iframe>
<script>
  let interval = window.setInterval(trackClick, 100);
  let i = 0;
  function trackClick() {
  if(document.activeElement == document.querySelector("#my-iframe")) {
  	i++
  	alert("clicked "+ i);
  	window.focus();
   }
 }
</script>
Try it Yourself »
Share

How to detect click inside iframe using JavaScript

0
How to detect click event inside iframe using JavaScript. Suppose you have five iframe el…
asked
0 answers

Write an Answer

Related Posts
Write an answer
back