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
- How to highlight searched text using JavaScript
- Automatically refresh or reload a page using JavaScript
- How to set an HTML element’s class using JavaScript
- How to create an auto-resize Textarea in JavaScript
- Scroll to a specific element using 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..!! 🙂