Benbob
Benbob

Reputation: 14264

jQuery set iFrame onLoad attribute

I need to trigger a function when the iframe loads a second time (the user clicks some link in the iframe). When the iframe page changes I can set the window location to the iframe src.

What I thought would be best is to set an onLoad attribute on the iframe element after the first load. I guess I would need the live event to tell when the iframe has been created, since it's dynamic.

This is what I had in mind:

$(document).ready(function() {
    $('#tenant_login').fancybox({type:'iframe'});
    $('#tenant_login').click(function() {
        $('#fancybox-frame').attr('onload', function() {
            window.location = $('#fancybox-iframe').attr('src');
        });
    });
});

If it matters the iframe is not cross domain.

Upvotes: 1

Views: 11405

Answers (2)

Benbob
Benbob

Reputation: 14264

If you have control of the iframe content, as I did setting a target="_top" attribute on the hyperlink means the browser will open the link in the browser window rather than the iframe.

Main document:

<html>
  <body>
     <h1>The Main Page</h1>
     <iframe src="myIframe.html" />
  </body>
<html>

Iframe document:

<h2>The IFRAME</h2>
<a href="something.html" target="_top" >
  This will open in the browser window rather than any iframe it exists in.
</a>

If you can't put target="_top" on the links of the iframe DOM you will need to capture the click events with javascript from the parent DOM.

Upvotes: 0

Stefan Dunn
Stefan Dunn

Reputation: 5513

$("#fancybox-iframe").load(function(){
            window.location = $('#fancybox-iframe').attr('src');
});

This will allow you to redirect the parent window when the iframe loads a different page.

Upvotes: 2

Related Questions