February 26, 2013

Add click event to iframe

Question by user1170330

I want to add a click event to an iframe. I used this example and got this:

$(document).ready(function () {
   $('#left').bind('click', function(event) { alert('test'); });

<iframe src="left.html" id="left">

But unfortunately nothing happens.
When I test it with another element (e.g. a button), it works:

<input type="button" id="left" value="test">

Answer by Starx

The actual problem is that, the click event does not bind to the DOM of the iframe and bind() is deprecated, use .on() to bind the event. Try with the following codes and you will find the borders of the iframe clickable getting that alert.

$('#left').on('click', function(event) { alert('test'); });

Demo of that Issue

So how to get it done?

How you should do is, create a function on iframe page, and call that function from that iframe page.

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+


Please fill the form - I will response as fast as I can!