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">
</iframe>
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'); });
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.