javascript - how to bind fancybox to dynamic added element? -


i use jquery fancybox 1.3.4 pop form.

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

like : first append element body use jquery,

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

and call fancybox,

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

but fancybox don't work dynamic added element.

and can't call fancybox element?

i come china. english poor, please forgive me.

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

1: upgrade jquery v1.7.x (if haven't yet)

2: set script using jquery api on() + focusin event.

to make work need find parent element of elements class="ajaxfancybox" per code above (or parent of parent need it) , attach jquery on() example, having 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> 

.. apply on() , focusin event element id="container" (the parent) in example above, like:

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

you can apply fancybox option need. additionally may have different scripts different type of content (inside 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: example above won't work on chrome. workaround add tabindex attribute of elements bound 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 issue , work (as far know) in browsers including ie7+.

see demo page here

update: march 07, 2012.

i told method works when add new content page not when replace content of page.

the method works on either of 2 scenarios mentioned above. make sure new replacing content loaded inside container applied .on() method.

see demo

the tabindex workaround chrome applies.


Comments

Popular posts from this blog

linux - xterm copying to CLIPBOARD using copy-selection causes automatic updating of CLIPBOARD upon mouse selection -

c++ - qgraphicsview horizontal scrolling always has a vertical delta -