Table Maker3schools TranslateImage CompressorFavicon Icon GeneratorCrop & Resize Image
Apu November 20, 2022 . #HowTo . #Iframe

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="" width="200" height="200"></iframe>
 window.addEventListener("blur", () => {
  setTimeout(() => {
    if(document.activeElement.tagName === "IFRAME") {
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>
  let interval = window.setInterval(trackClick, 100);
  let i = 0;
  function trackClick() {
  if(document.activeElement == document.querySelector("#my-iframe")) {
  	alert("clicked "+ i);
Try it Yourself »
AI Answer
Write Your Answer
View All