How to bind fancybox to dynamic added element?

后端 未结 5 673
梦谈多话
梦谈多话 2020-11-22 07:03

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.

5条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-22 07:47

    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:

    
    

    .. 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

    
    

    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.

提交回复
热议问题