Search code examples
javascriptjqueryiframe

Add click event to iframe


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">

Solution

  • You could attach the click to the iframe content:

    $('iframe').load(function(){
      $(this).contents().find("body").on('click', function(event) { alert('test'); });
    });
    

    Note: this will only work if both pages are in the same domain.

    Live demo: http://jsfiddle.net/4HQc4/