How to bind fancybox to dynamic added element?

caochao picture caochao · Jan 31, 2012 · Viewed 31.8k times · Source

I use jquery fancybox 1.3.4 as pop form.

but I found fancybox can't bind to element dynamic added. for example when I add a html element to current document.

like this: first I append a element to body use jquery,

  $(document.body).append("<a href="home/index" class="fancybox"/>");

and I call fancybox,

  $(".ajaxFancyBox").fancybox({padding: 0});

but fancybox don't work with dynamic added element.

and I can't call fancybox from this element?

Answer

JFK picture JFK · Jan 31, 2012

The easiest way to bind fancybox (v1.3.x) to dynamically added elements is:

1: Upgrade to jQuery v1.7.x (if you haven't yet)

2: Set your script using jQuery API on() + the focusin event.

To make it work you need to find the parent element of your elements with class="ajaxFancyBox" as per your code above (or the parent of the parent as you need it) and attach jQuery on() to it so for example, having this html:

<div id="container">
 <a class="ajaxFancyBox" href="image01.jpg">open image 01</a>
 <a class="ajaxFancyBox" href="image02.jpg">open image 02</a>
</div>

.. we will apply on() and focusin event to the element with id="container" (the parent) as in the example above, like:

$("#container").on("focusin", function(){
 $("a.ajaxFancyBox").fancybox({
  // fancybox API options here
  'padding': 0
 }); // fancybox
}); // on

You can apply any fancybox option as you need. Additionally you may have different scripts for different type of content (inside the on() method) like:

$("#container").on("focusin", function(){
 $("a.ajaxFancyBox").fancybox({
  // fancybox API options here
  'padding': 0
 }); // fancybox
 $("a.iframeFancyBox").fancybox({
  // fancybox API options here
  'padding': 0,
  'width': 640,
  'height': 320,
  'type': 'iframe'
 }); // fancybox
}); // on

IMPORTANT: the example above won't work like that on Chrome. The workaround is to add the tabindex attribute to all of your elements bound to fancybox like

<div id="container">
 <a tabindex="1" class="ajaxFancyBox" href="image01.jpg">open image 01</a>
 <a tabindex="1" class="ajaxFancyBox" href="image02.jpg">open image 02</a>
</div>

that solves the issue and will work (as far as I know) in most browsers including IE7+.

See my demo page here

UPDATE: March 07, 2012.

I was told that this method only works when you add new content to the page but not when you replace the content of the page.

The method actually works on either of the two scenarios mentioned above. Just make sure that the new replacing content is also loaded inside the container where you applied the .on() method.

See demo

The tabindex workaround for Chrome also applies.