Clue Mediator

How to add an event listener to iframe

📅March 24, 2022

We're going to show you how to add an event listener to an iframe. In this article, we will see two different methods to add an event listener to an iframe.

Checkout more articles on JavaScript

Using JavaScript

You can use the following code, if you want to use the pure vanilla JavaScript.

var iframe = document.getElementById('myiFrame');
iframe.contentWindow.body.addEventListener('keydown', handler);

function handler() {
    console.log('keydown works');
}

Using jQuery

Use the following code, if you want to use the jQuery code.

$('#myiFrame').load(function () {
  var contents = $(this).contents(); // contents of the iframe
  $(contents).find("body").on('keydown', function (event) {
    console.log('keydown works');
  });
});

I hope you find this article helpful.
Thank you for reading. Happy Coding..!! 🙂