views:

31

answers:

2

Hi folks. I'm using Fancybox (http://fancybox.net) to pop open an iFrame. In order to do so, I create a link with a class set to "item_pop" as so:

<div id="events">
    <a href="http://www.example.com" class="item_pop">My Link</a>
</div>

I then have some JavaScript in the footer that supports this:

jQuery(".item_pop").fancybox({
        'width'             : 900,
        'height'            : 500,
        'autoDimensions'    : true,
        'autoScale'         : true,
        'transitionIn'      : 'elastic',
        'titleShow'         : false,
        'transitionOut'     : 'elastic',
        'centerOnScroll'    : true,
        'type'              : 'iframe'
});

Ok, so this all works swimmingly. The problem is that I use jQuery to create additional links like this on the fly as so:

jQuery(document).ready(function(){
        update_seconds = 20;
        update_duration = update_seconds * 1000;

        window.setInterval(reload_events, update_duration);
});

function reload_events()
{       
        jQuery.post("http://www.example.com", {type:'any'}, function(data){
            var events = eval(data);
            var html = '';

            for(var i=0; i<events.length; i++){
                var evt = events[i];

                html += '<a href="http://www.example.com" class="item_pop">My Link</a>';
            }

            jQuery('#events').children().remove();
            jQuery('#events').append(html);
        });
}

This actually displays the links to screen, but when you click on them they don't pop up the iFrame. Instead they open the intended page as a new page, rather than as an iFrame inside the existing page.

Any ideas? Cheers

A: 

The problem as i see it is that fancybox doesn't know anything about these additional links, as the JavaScript is only interpreted as the page loads. You need to use jQuerys .Live() so that fancybox will be aware of any dynamically created content.

Doozer1979
A: 

what's happening is that jQuery(".item_pop") finds elements matching the selector at that time and binds to those. Since you're creating new elements later, you need to bindto them.

After this call:

jQuery('#events').append(html);

You need to run the .fancybox() call again, on this set of new elements:

jQuery("#events .item_pop").fancybox({ ... });

Or alternatively (and less efficient) you can use the .livequery() plugin, like this:

jQuery(".item_pop").livequery(function() {
  jQuery(this).fancybox({
    'width'             : 900,
    'height'            : 500,
    'autoDimensions'    : true,
    'autoScale'         : true,
    'transitionIn'      : 'elastic',
    'titleShow'         : false,
    'transitionOut'     : 'elastic',
    'centerOnScroll'    : true,
    'type'              : 'iframe'
  });
});
Nick Craver
Hi, thanks. I used your suggestion to run the Fancybox call again after the HTML was output to screen and it worked a treat. Cheers
Craig