display jquery prettyPhoto lightbox in iframe parent

Andrew picture Andrew · Sep 27, 2009 · Viewed 21.7k times · Source

I am using jquery prettyphoto 2.5.3 and I was wondering how I can get the light box to display in the parent window of an iframe when an image link inside the iframe is selected?

Here's my code:

Page in the iframe:

<html>
<head>
    <script src="js/jquery-1.3.2.min.js" type="text/javascript"></script>
    <link rel="stylesheet" href="css/prettyPhoto.css" type="text/css" media="screen"/>
    <script src="js/jquery.prettyPhoto.js" type="text/javascript"></script>
</head>

<body>
    <a href="animage.jpg" rel="prettyPhoto">
                <img src="animage.jpg" height="200" width="200"/>
    </a>
            <script type="text/javascript" charset="utf-8">
              $(document).ready(function(){
                 $("a[rel^='prettyPhoto']").prettyPhoto();
              });
    </script>
</body>

When I load up this page on its own the lightbox works fine.

Iframe code:

<html>
<head>
</head>

<body>
    <iframe src="inner.html"/>
</body>
</html>

However, when I load up the page with the iframe and click on the image link in the page that is in the iframe I want the lightbox to display in the parent window and not in the iframe.

Answer

Waleed Amjad picture Waleed Amjad · Sep 27, 2009

Try this selector: $("#myid", top.document)

The top.document tells the selector to target the myid element which exists in the topmost document (your parent page). In order for this to work, jQuery must be loaded in the file which is viewed through the iframe.

Source: http://groups.google.com/group/jquery-en/browse_thread/thread/5997ef4a60a123af?pli=1

EDIT

Ok the only way this will work is:

  1. Remove the following code from your real page (inner.html, the one contained in the iframe):

    <script type="text/javascript" charset="utf-8">
      $(document).ready(function(){
             $("a[rel^='prettyPhoto']").prettyPhoto();
          });
    

  2. Now in your iframe page, add:

    <script src="js/jquery-1.3.2.min.js" type="text/javascript"></script>
    <link rel="stylesheet" href="css/prettyPhoto.css" type="text/css" media="screen"/>
    <script src="js/jquery.prettyPhoto.js" type="text/javascript"></script>
    
  3. Also add the following JS code:

    $(function() {
        $("iframe").contents().find("a[rel^='prettyPhoto']").click(function() { $(this).prettyPhoto(); return false; } );
    });
    

That should do the trick, but it will then ONLY work for the iframe page, and not directly from within the real page.