rhapsodyn
rhapsodyn

Reputation: 3352

Can jQuery bind to an iframe's onload event?

I know that jQuery can’t bind to a file input’s onchange event. Is it also the case that it can’t bind to an inframe’s onload event?

With this HTML,

<iframe src="http://jsfiddle.net" onload="alert('js alert');"></iframe>

and this javascript,

$("iframe").live("onload",function(){alert('jq alert');});

I get the alert js alert, not jq alert, so jQuery is not binding to the onload event.

Demo on JSFiddle.

I can’t understand why jQuery cannot bind to the onload event in time (as ThiefMaster said). Is onload so different from other events?

Upvotes: 0

Views: 11271

Answers (2)

n8o
n8o

Reputation: 1943

In your code, you can't catch the onload event because the event already fired and flew away at that time.

Here is a solution to catch the event:

HTML

<iframe src=""></iframe>

JS

$(document).ready(function() {
  $("iframe").load(function() { alert('load complete'); });
  $("iframe").error(function() { alert('error occurs'); });
  $("iframe").attr("src", "http://google.com");
});

When you provide the src, the load/error event fired. So, before provide src, bind events you want to handle.

You can also use this trick to <img>!

Upvotes: 0

ThiefMaster
ThiefMaster

Reputation: 318508

The event has already fired at the point where you register the event handler. If you need to handle the onload event and want to avoid ugly inline event handlers, create the iframe through jQuery and attach the event handler before setting the url or attaching it to the document.

Upvotes: 3

Related Questions