Blog of Alexander Mamchenkov

… mammoth cave …

jQuery fancybox with ajax

Posted on May 21, 2010 in Technology and has 104 comments

I was fighting with bloody fancybox jQuery plugin the whole day yesterday. While it was working find on loading large image popups in normal scenarios, it was refusing to work when content was supplied through AJAX, meaning that DOM was altered after the fancybox was initialized.

Have tried several methods like using livequery plugin for jQuery, putting fancybox init in success callback of AJAX request and a lot of other things – non helped.

Finally, the solution was to put fancybox reinit in success callback of AJAX request, but not directly. Instead I had to use setTimeout method with delay of 600 to reinit fancybox as follows:

$.getJSON(ajax_url,function(HTML) {

    // populate my DOM with some HTML here

    // make fancybox reinit
    setTimeout(
        function() {
            $(\"a.some_fancy_box_element_class\").fancybox();
        },
        600
    );
});

This way it is working fine for me. Not sure why timeout is needed and what is the best delay time though. Can assume that DOM needs some time to insert all the elements and that by default fancybox was faster to check it than the actual update was finished.

Keep in mind that standard fancybox init should still remain in document ready event to adjust all elements on initial page load complete.

Comments

104 Responses to “jQuery fancybox with ajax”

  1. alan
    June 6th, 2010 @ 1:54 am

    THANK YOU. You just removed a roadblock that cost me the better part of a day.

  2. cindy
    June 9th, 2010 @ 6:19 am

    Thank you!!! I have been struggling with this for hours (well, it seems like hours). This is the only solution I’ve found that actually works.

  3. Alexander Mamchenkov
    June 9th, 2010 @ 12:53 pm

    I am glad this worked for you.

    Just an additional note since it is related to what I was doing – this has nothing to do with fancybox, but rather with JS in general. I had few issues with Google Maps API when I was trying to fire some events immidiatelly, after adding setTimeout stuff – everything was working fine.

  4. hernan
    June 14th, 2010 @ 4:59 am

    Muchas gracias.

    me ha servido bastante tu idea..

    atte

    Hernan

    desde Chile!

  5. vfbrito
    July 19th, 2010 @ 9:40 pm

    Obrigada!
    You saved my day :D

  6. Guillermo
    August 15th, 2010 @ 7:32 am

    I don’t understand in that part of the website, i may put this code.

    In the index.php? in the page of my call of AJAX?

    //populate my DOM with some HTML here <- Some idea?

    Thank you!

  7. Alexander Mamchenkov
    August 15th, 2010 @ 8:23 am

    You put this code as a part of your Javascript (either embeded in the page or loaded from separate file).

    With regards to populating DOM, this is up to you. I used it to load additional pictures from the server on demand. Fancybox was just displaying bigger images on click.

  8. Guillermo
    August 15th, 2010 @ 9:47 pm

    $.getJSON(ajax_url,function(HTML) {
    // populate my DOM with some HTML here

    // make fancybox reinit
    setTimeout(
    function() {
    $(“a[rel=archivoImagenDelDia]”).fancybox();
    },
    600
    );
    });

    That is ok?, really i don’t work for me.

  9. Alexander Mamchenkov
    August 16th, 2010 @ 1:00 am

    do you user correct URL? Does jQuery finds a correct element?

    It is really hard to see anything here without a context.

  10. Guillermo
    August 16th, 2010 @ 6:28 am

    ok, i have a page index.php, where i have my javascript. In this page there is a one picture with the fancybox plugin. really this picture is the last picture of a gallery, the idea is show the album with AJAX, and apply the gallery fancybox plugin. Example: The image of the picture and in the bottom there is a link that say “Galery”. That link is AJAX, and will show the full galery. This galery should works with fancybox also.

    The code:

    function navegar(donde) {
    jQuery.ajax({
    url: donde+”.php?cache=”+Math.random(),
    dataType: “HTML”,
    success: function(datos){
    document.getElementById(‘principal’).innerHTML = datos;
    }
    });
    }

    $(document).ready(function() {

    $(“a#imagenDelDia”).fancybox({
    ‘transitionIn’ : ‘elastic’,
    ‘transitionOut’ : ‘elastic’,
    ‘titlePosition’ : ‘over’
    });

    $(“a[rel=archivoImagenDelDia]”).fancybox({
    ‘transitionIn’ : ‘fade’,
    ‘transitionOut’ : ‘fade’,
    ‘titlePosition’ : ‘over’,
    ‘titleFormat’ : function(title, currentArray, currentIndex, currentOpts) {
    return ‘Image ‘ + (currentIndex + 1) + ‘ / ‘ + currentArray.length + (title.length ? ‘   ‘ + title : ”) + ”;
    }
    });

    });

    Do you understand me? Thank you…

  11. Alexander Mamchenkov
    August 16th, 2010 @ 9:07 am

    As I understand, you have two fancybox links which you init in document.ready state and you have a function, which somehow changes the content of the links on some events. If this is right, then you need to modify the navegar function in a way:

    function navegar(donde) {
    jQuery.ajax({
    url: donde+”.php?cache=”+Math.random(),
    dataType: “HTML”,
    success: function(datos){
    document.getElementById(‘principal’).innerHTML = datos;
    // Reinit fancybox elements and do it with setTimeout here
    // something like
    setTimeout(
    function() {
    $(“a[rel=archivoImagenDelDia]”).fancybox(…);
    },
    600
    );

    }
    });
    }

    Hope this makes it more clear.

  12. Alexander Mamchenkov
    August 16th, 2010 @ 9:07 am

    Current theme kinda sux with nested comments :(

  13. Guillermo
    August 17th, 2010 @ 7:46 am

    Men!! Thank you so much!! You fixed it! Sorry for all, i am a freshman in the JQuery. :)

  14. Alexander Mamchenkov
    August 17th, 2010 @ 8:55 am

    I am happy that my help did work for you. You are always welcome. Good luck with jQuery :)

  15. Luisus
    August 31st, 2010 @ 8:22 am

    Thank you very much my friend!!

    You are my hero!

    :D

  16. Andrea Ferrari Toniolo
    September 4th, 2010 @ 4:10 am

    really thanks, it worked like a charm, and saved me

  17. anji
    December 13th, 2010 @ 12:55 pm

    Hi,
    i just want display my JSP field in a fancy box by using ajax callback methods,
    any sample code ,please help me

  18. Alexander Mamchenkov
    December 13th, 2010 @ 3:51 pm

    the code in the post should be right enough for you to do what you want.

    Make an ajax request using jQuery, supplying the URL of your JSP page, which should return some HTML with fancybox element in it. Reinit fancybox on successfull call and you are done.

  19. Tim Tessier
    December 23rd, 2010 @ 11:49 pm

    Just a thought, but could it be that the DOM is not fully loaded when the $.getJson is being called – would a $(document).ready(function(){}); pattern not be more appropriate?

  20. Julian
    January 21st, 2011 @ 8:12 pm

    Thank you!

    You have saved me serious heart ache. I’ll paraphrase your trick if I may for any one else looking for the solution…

    Top page that loads in browser:
    $(“a#editdetails”).fancybox({
    ‘hideOnContentClick': false,
    ‘scrolling’ : ‘no’,
    ‘overlayOpacity’ : 0.7,
    ‘overlayColor’ : ‘#6d6e71′
    });

    In the end of the HTML that loads via AJAX:
    $(document).ready(function(){

    // RE-INITAILSE FANCYBOX BECAUSE
    // WE HAVE LOADED THE CONTENT WITH AJAX
    $(“a#editdetails”).fancybox({
    ‘hideOnContentClick': false,
    ‘scrolling’ : ‘no’,
    ‘overlayOpacity’ : 0.7,
    ‘overlayColor’ : ‘#6d6e71′
    });

    });

    You need to put the fancybox code again at the end of the ajax HTML in a document ready call. I didn’t need a timeout, I jsut made sure the call was the last thing in the ajax content

  21. gustav
    February 8th, 2011 @ 12:47 am

    setTimeout(
    function() {
    God bles you Man! Ingenious Solution!!
    },
    600
    );

  22. Alexander Mamchenkov
    February 8th, 2011 @ 1:41 pm

    Glad it worked out for you

  23. josé damián garrido
    February 11th, 2011 @ 6:51 pm

    excelente!! funciona!

  24. Romain Ménard
    February 13th, 2011 @ 1:35 am

    Thanks a lot ! I was wondering how to do this since a long time ! It works perfectly.

  25. Ross
    February 17th, 2011 @ 5:15 am

    This solution (re-adding the fancybox initialization inside the included AJAX content) worked perfect form me…I’d tried 6+ other solutions and nothing was working. Love it when there’s a simple fix….just sorry I didn’t think of it myself. :) Thanks a million.

  26. Farhan
    February 21st, 2011 @ 2:14 pm

    Thank you.

    Thais worked for me.

  27. Simon
    March 9th, 2011 @ 11:40 pm

    This seems like the answer to my problem but I can’t make it work.

    I have a front page with navigation that calls (using AJAX) some content to a div. Inside that retrieved content I have another link that I want to call a group of images to be displayed using fancybox.

    If I try to call the images through fancybox from a link in the front page it works, when the link is called using AJAX it doesn’t.

    I think the answer is on this page somewhere but as an amateur I’m really struggling. Can someone spell it out!

    Where do I put which bits of code?

    Thanks.

  28. Alexander Mamchenkov
    March 10th, 2011 @ 5:54 pm

    Hi,

    One way: put a fancybox init inside content that is being inserted in the div, so it will init fancybox after content is loaded
    Second way: put fancy box init inside a success trigger for AJAX call with timeout, so that when AJAX call finishes, it reloads all fancybox in the page.

  29. Simon
    March 10th, 2011 @ 10:34 pm

    Sorry to be so slow to take this on board but I’ve tried various ways and still can’t make it work. I have this in my front page header (along with the links to jquery.fancybox-1.3.4.pack.js etc):

    $(document).ready(function() {

    $(“a[rel=example_group]”).fancybox({
    ‘transitionIn’ : ‘elastic’,
    ‘transitionOut’ : ‘elastic’,
    ‘titlePosition’ : ‘over’,
    ‘titlePosition’ : ‘outside’,
    ‘speedIn’ : 600,
    ‘speedOut’ : 400,
    ‘hideOnOverlayClick’ : true, });
    });

    Then a link in the body where AJAX calls a PHP page which echoes: Click here

    When I click on ‘Click here’ the image just loads up in a new window.

    Further advice would be much appreciated.

    Thanks.

  30. Alexander Mamchenkov
    March 11th, 2011 @ 11:51 am

    Your problem is that fancybox init happens on page load, while fancybox link appears after through AJAX and is not converted to fancybox element. What you need to do is to reinit fancybox after the ‘Click here’ link is inserted into the document. The suggestion here is that you push the fancybox init (that you described above) along with the ‘Click here’ link.

  31. Simon
    March 11th, 2011 @ 4:49 pm

    Thank you for being so patient with me Alexander. I had tried what I think you are suggesting but still no luck. Here is the code that is pushed back to the front page:
    <!–

    $(document).ready(function() {

    $(“a[rel=example_group]”).fancybox({
    ‘transitionIn’ : ‘elastic’,
    ‘transitionOut’ : ‘elastic’,
    ‘titlePosition’ : ‘over’,
    ‘titlePosition’ : ‘outside’,
    ‘speedIn’ : 600,
    ‘speedOut’ : 400,
    ‘hideOnOverlayClick’ : true, });
    });

    Click Here

    –>
    Can you spot the problem? If not I think I’ll have to give up!

    Thanks again.

  32. Alexander Mamchenkov
    March 13th, 2011 @ 11:17 am

    Hi,

    it is very hard to troubleshoot by small portions of code. If you have the page public – share the URL to check it all.

    Sometimes with AJAX calls problems are small, simple, but very hard to find out. Check that JS doesn’t have any errors (try out Firebug for JS troubleshooting).

    Giving up is very easy )

  33. n002213f
    March 14th, 2011 @ 6:21 pm

    bool helpful = true;
    while(helpful) {
    printf(“Thanks a lot !”);
    }

  34. Alexander Mamchenkov
    March 15th, 2011 @ 10:24 am

    :-)

  35. Simon
    March 15th, 2011 @ 11:55 pm

    Hi Alexander,

    Actually I don’t intend to give up but I just don’t want to waste too much of your time.
    The site I am working on isn’t live but I have uploaded a simple example to demonstrate the problem: http://www.backdropdesign.co.uk/sandbox/

    Hopefully this should clearly show where I am going wrong. The link in the main content works as it is there on page load but the links called with AJAX don’t.

    The code is probably messy. Like I said, I am an amateur!!

    Thanks,
    Simon

  36. Alexander Mamchenkov
    March 16th, 2011 @ 8:44 pm

    I see it doesn’t work.

    In you AJAX target page:
    – move JS to be below the links (at the bottom of the page)
    – replace the JS with:

    $(function() {
    setTimeout(
    function() {
    $(“a[rel=example_group]“).fancybox({
    ‘transitionIn’ : ‘elastic’,
    ‘transitionOut’ : ‘elastic’,
    ‘titlePosition’ : ‘over’,
    ‘titlePosition’ : ‘outside’,
    ‘speedIn’ : 600,
    ‘speedOut’ : 400,
    ‘hideOnOverlayClick’ : true, });
    },
    600
    );
    });

    And try to see if it will work

  37. Simon
    March 16th, 2011 @ 10:51 pm

    Still not working I’m afraid.
    The new test is uploaded (with new image showing the AJAX page). I’d be very grateful if you could give it one more look.
    Thank you.
    Simon

  38. Alexander Mamchenkov
    March 17th, 2011 @ 10:05 am

    Also try referensing by class or id, not by rel. Make links of class=fancybox and try that way.

  39. Simon
    March 24th, 2011 @ 11:16 pm

    Still didn’t work unfortunately. I’ve found a work around for the project that doesn’t use AJAX but I will keep trying to resolve this problem.

    Thanks for all your help.

    I’ll post back if I get it working!!

  40. Ahsan Khan
    April 1st, 2011 @ 2:43 pm

    I very glad for fanceybox working with ajax, but my problem is that where i put this code.

    I have
    header.php(it is contain all my document ready function, CSS links, navigation, JS link etc)
    my_profile.php(where ajax function call, here is div id=ReloadThis)
    ajax.js(this conatin my Ajax() function )
    response.php (Ajax response coming from this file )

    var $j = jQuery.noConflict();
    $j(document).ready(function() {
    $j(“.image_lightbox”).fancybox({
    ‘width’ : 550,
    ‘height’ : 700,
    ‘autoScale’ : false,
    ‘transitionIn’ : ‘none’,
    ‘transitionOut’ : ‘none’,
    ‘type’ : ‘iframe’
    });
    }

    setTimeout(function() {Ajax();}, 10000);

  41. Alex Hughes
    April 1st, 2011 @ 3:30 pm

    Thanks Alexander!

    Also, for those using the jquery .load function.

    $(‘#the_post’).load(“http://site.com/load #content”,
    function() { setTimeout(function() {$(“.lightbox a”).fancybox();},600); }
    );
    return false;

  42. Alexander Mamchenkov
    April 3rd, 2011 @ 12:14 pm

    this code should go in response, so it is pushed through via AJAX along with other stuff you send through

  43. Alexander Mamchenkov
    April 4th, 2011 @ 10:37 am

    good to know as well, thanks :)

  44. Sarita
    April 6th, 2011 @ 11:19 am

    Thanks Alexander for the solution… it works like miracle…

  45. Paul
    April 23rd, 2011 @ 7:49 pm

    Hi Alexander, thanks for such a great blog.
    I have studied the trail above and still cannot get mine to work (there is probably a screw loose somewhere in my brain).

    The idea is to show a category of products with AJAX and then show a selected product with fancybox.
    My ajax code is as follows:
    function showCategory(id, title)
    {
    var params = ‘id=’ + id + “&title=” + title;
    var HTML = $.ajax({
    type: “POST”,
    url: “utils/get-category.php”,
    data: params,
    async: false
    }).responseText;
    document.getElementById(‘main_display_area’).innerHTML = HTML;
    }

    In the header of my main HTML I have the following code for fancybox:

    $(document).ready(function()
    {
    $(“a.ajax”).fancybox({
    ‘width’ : 500,
    ‘height’ : 500,
    ‘autoScale’ : false,
    ‘transitionIn’ : ‘none’,
    ‘transitionOut’ : ‘none’,
    ‘type’ : ‘iframe’
    });
    }) ;

    In the get-catgory.php HTML I have the following call for the link:

    “;

    In the head of get-product.php I have the following for fancybox (taken from your blog):

    $.getJSON(ajax_url, function(HTML)
    {
    setTimeout(
    $(“a.ajax”).fancybox({
    ‘width’ : 500,
    ‘height’ : 500,
    ‘autoScale’ : false,
    ‘transitionIn’ : ‘none’,
    ‘transitionOut’ : ‘none’,
    ‘type’ : ‘iframe’
    }), 600);
    });

    The categories show fine with AJAX and the product shows in a new tab in my explorer. What am I doing wrong?

    Any help would be greatly appreciated?
    Thanks,
    Paul.

  46. Paul
    April 23rd, 2011 @ 7:53 pm

    PS: just noticed the link code was filtered from my post above. Here it is again:

    Product Image

    Thanks,
    Paul.

  47. Paul
    April 23rd, 2011 @ 7:56 pm

    Oops. It really doesn’t like HTML anchor data in the posts: anyway I used the ajax class in my A link.

  48. Paul
    April 23rd, 2011 @ 10:22 pm

    Just one more thing Alexander.
    After loading the category (ajax) with all the products, I noticed that the page source has DIV tags at the end with the following IDs:
    fancybox-tmp
    fancybox-loading
    fancybox-overlay
    fancybox-wrap
    fancybox-outer
    fancybox-bg-n
    fancybox-bg-ne
    fancybox-bg-e
    fancybox-bg-se
    fancybox-bg-s
    fancybox-bg-sw
    fancybox-bg-w
    fancybox-bg-nw
    fancybox-content
    fancybox-close
    fancybox-title

    If I remove all the tags (by saving the file and then running from disk), then it works.
    I’m a little lost here.
    I have tried all the suggestions in this trail and nothing is working. Also tried many other pieces of code from the internet. No luck!
    Regards,
    Paul.

  49. Alexander Mamchenkov
    April 25th, 2011 @ 11:11 am

    first of all, instead of using:

    function showCategory(id, title)
    {
    var params = ‘id=’ + id + “&title=” + title;
    var HTML = $.ajax({
    type: “POST”,
    url: “utils/get-category.php”,
    data: params,
    async: false
    }).responseText;
    document.getElementById(‘main_display_area’).innerHTML = HTML;
    }

    do the following:

    function showCategory(id, title)
    {
    $.post(“utils/get-category.php”,{ id: id, title: title }, function(data) {
    $(‘#main_display_area’).html(data);
    });
    }

    Then, as I understand, the get-category returns HTML with links to products (fancybox links) and the get-product returns the product itself. So you need to put the setTimeout reinit of fancybox in get-category response, since the fancybox links are added during this call, not by get-product.

  50. Alexander Mamchenkov
    April 25th, 2011 @ 11:13 am

    anyhow I got the point :)

  51. Paul
    April 27th, 2011 @ 9:08 am

    Thanks Alexander, you understood it correctly.
    You really know your stuff mate! That worked like a charm.

    I’m so happy – Yupeee!!

  52. Alexander Mamchenkov
    April 27th, 2011 @ 10:06 am

    Actually, programming is not my topic, I am more on system administration, especially Linux. But as you can get, admins have to deal with all sort of crap, so you had to learn this as well ))))

    Glad it worked for you as well.

  53. Jordan
    June 9th, 2011 @ 11:04 pm

    Hi Alex,

    I’ve been struggling with this for a while, I was wondering if you had any insight into my problem, as your issue was the closest to mine that i could find on the net.

    Basically I’m loading images via ajax on my site. I’ve made a function that inits fancybox on the images within an article, I call this function on load and after the ajax call. The function contains this : $(‘#content’).find(‘a’).attr(‘rel’,’gallery’).fancybox();
    The function works no problem on load (fancybox works on load), however after the ajax call (and the timeout from your solution) the same function causes a “fancybox is not a method” error. I was wondering if you have any insight into this.

    You can find the site at http://www.weststreetmedia.ca

    Thanks,
    Jordan

  54. Alexander Mamchenkov
    June 10th, 2011 @ 7:58 am

    try to use some other, simple method of locating elements you need, instead of find. For example assign all A elements a specific class (smthing like ‘fancybox’) and then use $(‘.fancybox’).fancybox() to initiate fancybox. I bet that jQuery fails to find the elements and then fails to call fancybox() method.

  55. Jordan
    June 15th, 2011 @ 7:51 pm

    I’ll try it and let you know, thanks a lot :)

  56. Theo
    June 20th, 2011 @ 4:30 pm

    So Fancybox kinda needs an afterOnClosed event?

  57. Alexander Mamchenkov
    June 22nd, 2011 @ 10:03 am

    not exactly. It needs a re-init on all relevant elements which were supplied via AJAX call after the initial DOM loaded.

  58. Blog of Alexander Mamchenkov » jQuery dataTable and FancyBox
    June 23rd, 2011 @ 3:58 pm

    […] a short note as an addon to my post some time ago about fancybox and ajax: in case a you have a table where one of the columns contains links to fancybox popups or something […]

  59. Rico
    June 29th, 2011 @ 3:29 am

    Do you happen to know how to push an ajax form post into a fancybox iframe?

    This works to post form data to the fancy box:

    $(“#form_name”).bind(“submit”, function() {

    $.ajax({
    type : “POST”,
    cache : false,
    URL : “external_site_to_post_form_data”,
    data : $(this).serializeArray(),
    success: function(data) {
    $.fancybox(data);
    }
    });

    return false;
    });

    And this code works to load an external site into an iframe in the fancybox:

    jQuery(“#iframe”).fancybox({‘width': ‘70%’,’height': ‘100%’,’autoScale': true,’type':’iframe’});

    But what I need is the functionality of both at the same time. What I want to do is load a hosted merchant account form in a fancybox but I need to post certain variables to that page.

    This is where I am at right now (which is not working but I know it’s close):

    $(“#form_name”).bind(“submit”, function() {

    $.ajax({
    type : “POST”,
    cache : false,
    URL : “external_site_to_post_form_data”,
    data : $(this).serializeArray(),
    success: function(data) {
    $.fancybox({
    ‘content’ : data, <—- I KNOW THIS IS WRONG
    'width' : '70%',
    'height' : '100%',
    'autoScale' : true,
    'type' : 'iframe'
    });
    }
    });

    return false;
    });

    If you have any ideas on how I can send the data while at the same time sending it to an iframe inside the fancybox I would greatly appreciate it.

  60. Alexander Mamchenkov
    June 29th, 2011 @ 12:53 pm

    So in your case the fancybox content is not populated with data?
    If yes, maybe you can try some workaround like setting fancybox content to empty content and then using jQuery selector populate the iframe with needed data?

    Something like:

    $(“#form_name”).bind(“submit”, function() {

    $.ajax({
    type : “POST”,
    cache : false,
    URL : “external_site_to_post_form_data”,
    data : $(this).serializeArray(),
    success: function(data) {
    $.fancybox({
    ‘content’ : ”,
    ‘width’ : ‘70%’,
    ‘height’ : ‘100%’,
    ‘autoScale’ : true,
    ‘type’ : ‘iframe’
    });
    $(‘#your_iframe_id’).html(data);
    }
    });

    return false;
    });

  61. Rico
    June 29th, 2011 @ 4:14 pm

    Nope that didn’t work either. I am beginning to think that this just can’t be done with current modal tech. Which I really hate to do….lol.

  62. Sorin
    July 11th, 2011 @ 3:07 pm

    Thanks a lot. That was really helpful

  63. Dmitry Romanovsky
    July 22nd, 2011 @ 4:30 pm

    hi Alexander!

    This is really something precious, may i ask you to post a demo for your idea?
    That would be great! I’m not a guru with jquery, that would really cut off a lot of questions..

    Thanks!
    Dmitry

  64. Michael
    July 22nd, 2011 @ 5:01 pm

    I was trying to do something similar. Wanted to load form content from a template HTML file into a fancybox. Wanted it dynamic so i could use the same script to load forms dynamically without having to duplicate the same code over and of (evetually, will write this into a class lib, for now, it’s just inline… anyhoo). I had a hard time for a while, and found your code, but that didn’t work either. This, however, did. Thought I’d post it here for posterity if nothing else:

    $(“.formHandler”).bind(“click”, function() {
    $.fancybox.showActivity();
    $.get(‘templates/contact.cfm’,{mode:”ajax”},function(HTML){
    $.fancybox(HTML);
    });
    });

    This worked exactly perfectly for me. No other options configured and no local DOM element holding the content. Basically, this force feeds the downloaded AJAX content into fancybox rather than populating a DOM element and then opening it. The issue I was having with that wasn’t that it wouldn’t work, but that fancybox wouldn’t size correctly… Anyway, that’s the solution that suited me, enjoy!

  65. Alexander Mamchenkov
    July 26th, 2011 @ 3:05 pm

    Hi Dmitry,

    unfortunately the project, for which I used this is private and is not accessible for everyone, but I will think of something. Maybe I will just combine this few things into couple of HTML files and upload them somewhere here.

  66. Alexander Mamchenkov
    July 26th, 2011 @ 3:07 pm

    Oh, that looks great, never thought of it this way. Thanks for sharing the code. Looks pretty strait forward.

  67. zima101
    July 28th, 2011 @ 5:28 pm

    Hi,

    Am trying to attach fancybox event to ajax content – but can work it out

    my ajax call looks like

    $.get(loadUrl, function(data)
    {
    var caldiv = document.getElementById(‘cal’);
    caldiv.innerHTML = data;
    },
    function() { setTimeout(function() {$(“.popupfancy a”).fancybox();},600); }
    );

    all links in response have class=popupfancy

    can you tell what IM doing wrong?

  68. Alexander Mamchenkov
    July 29th, 2011 @ 9:18 am

    As I didn’t clearly understood what exactly you are doing, I assume that you get content of caldiv through AJAX, which has some A elements of class popupfancy, which you want to be initiated as fancybox.

    First of all, a general advice – if you use jQuery, try to stick with it’s selectors, instead of getElementsById and so on. Second is that you missed up a bit with setTimeout. The code above should look similar to this:

    $.get(loadUrl, function(data) {
    $(‘#caldiv’).html(data);
    setTimeout(function $(‘.popupfancy’).fancybox();},600);
    });

  69. zima101
    July 29th, 2011 @ 2:30 pm

    thanks Alexander – fbox links works great

  70. Bhavesh
    August 12th, 2011 @ 12:19 pm

    Worked for me!!
    Thanx alot :D

  71. Matt
    August 13th, 2011 @ 6:58 pm

    Thanks a lot Alexander. You saved my Saturday!

  72. Len
    August 14th, 2011 @ 3:19 pm

    Hi Alexander,

    I have code on my home page to open a FancyBox to display the details of any news item link clicked. The page called fetches/displays the news info from my database. This works great if I use the iFrame version of FancyBox. However, if the news item displayed includes a PapPal buy-now button, PayPal will not handle the click-thru. For security reasons PayPal doesn’t allow you to call its services from an iFrame. So what I would like to do is replace the call to open FancyBox in an iFrame with a call to open it via AJAX.

    Here’s the iFrame version that works fine:

    $(‘.news_display_modal’).click(function(){ //listen for a click on news item

    var target = $(this).attr(“id”); //Get the ID of the news link clicked
    target = target.replace(“newsID”,””); //Zap the leading “newsID” text

    $.fancybox({ //Open the modal FancyBox
    ‘href’ : ‘/news_display_modal.asp?cid=’ +target,
    … other settings omitted for brevity …
    ‘type’ : ‘iframe’
    });

    How do I do it via AJAX?

    Thanks in advance for any suggestions.

  73. Alexander Mamchenkov
    August 15th, 2011 @ 1:21 am

    Hi,

    As far as I remember, you just need to create a simple link to a URL where AJAX call should be made and init it to fancy box. For example:

    <a href=’/news_display_modal.asp?cid=my_new_id1′ class=’fancybox’>Click for details</a>

  74. Len
    August 15th, 2011 @ 6:37 am

    Ah, but there’s the rub. I’ve tried all sorts of code combinations to open the news_display_modal.asp?cid=my_new_id1 page in Fancy Box in AJAX mode but none have worked. Sample code would be much appreciated.

  75. Alexander Mamchenkov
    August 15th, 2011 @ 3:58 pm

    Have you tried specifying the type=’ajax’ in an A element to force AJAX as per fancybox documentation? Also, please check with Firebug that there are no errors in the page that might stop fancybox from initiating correctly.

  76. Marcel
    September 26th, 2011 @ 9:15 pm

    Thank you man :)

  77. jjozsi
    October 10th, 2011 @ 3:09 am

    Thanks for sharing this solution for this bug in fancybox!
    hi5

  78. Waqas
    December 11th, 2011 @ 10:27 am

    hi,
    very nice post, i was looking for this for quiet long time but i have come across one more major problem that when you trigger the fancybox function after ajax call, it works fine but what if you have one more ajax call inside facybox init.
    i guess so after execution facybox init does not return control back to ajax so the ajax calls inside facybox are executed.

  79. jose
    December 13th, 2011 @ 3:04 am

    ok i need some help with this i’m going crazy here i need the fancybox to work with ajax. this is the pagination then it displays content and content has a link. i want to be able to click on the link then the fancybox will popup or work but i cannot get it to work do not know where to put the $(“a.class”).fancybox({….});

    $(document).ready(function(){

    function loading_show(){
    $(‘#loading’).html(“”).fadeIn(‘fast’);
    }
    function loading_hide(){
    $(‘#loading’).fadeOut(‘fast’);
    }

    function loadData(page){
    loading_show();

    $.ajax
    ({
    type: “POST”,
    url: “the_url_data_page.php”,
    data: “page=”+page,
    success: function(msg)
    {

    $(“#container”).ajaxComplete(function(event, request, settings)
    {

    loading_hide();

    $(“#container”).html(msg);
    });//ajaxComplete

    }//success
    });
    }
    loadData(1); // For first time page load default results
    $(‘#container .pagination li.active’).live(‘click’,function(){
    var page = $(this).attr(‘p’);
    loadData(page);

    });

    $(‘#go_btn’).live(‘click’,function(){
    var page = parseInt($(‘.goto’).val());
    var no_of_pages = parseInt($(‘.total’).attr(‘a’));
    if(page > 0 && page <= no_of_pages){
    loadData(page);
    }else{
    alert('Enter a PAGE between 1 and '+no_of_pages);
    $('.goto').val("").focus();
    return false;
    }

    });

    });

    Thanks in advance for your help.

  80. Alexander Mamchenkov
    December 13th, 2011 @ 11:49 am

    As I assume your fancybox links come via AJAX and then inserted as a part of the content for #container. Then, after you do $(‘#container’).html(msg); you need to reinit fancybox inside that container. Try putting something like $(‘#container’).find(‘a.class’).fancybox(); right after you set the content. If it fails, try using setTimeout, so that all elements inside the container are inserted in the DOM prior to your call for fancybox.

    So in first version it should look like:
    $(‘#container’).html(msg);
    $(‘#container’).find(‘a.class’).fancybox();

    In second, you can try:
    $(‘#container’).html(msg);
    setTimeout(function () { $(‘#container’).find(‘a.class’).fancybox(); },600);

  81. jose
    December 14th, 2011 @ 9:29 pm

    Hello Alexander thanks for your reply i try both of them i get an empty display.

  82. jose
    December 14th, 2011 @ 9:40 pm

    ok i was able to get it to display the links but still not working. I added the links to fancybox this is what i have.

  83. jose
    December 15th, 2011 @ 4:49 am

    Thanks Alexander I found the problem looks like i had a conflict with my other .js files. its working now.. THANK YOU. again.

  84. jose
    December 16th, 2011 @ 3:25 am

    hello Alex,

    Is their a way that i can add a search form to this?

    $(document).ready(function(){

    function loading_show(){
    $(‘#loading’).html(“”).fadeIn(‘fast’);
    }
    function loading_hide(){
    $(‘#loading’).fadeOut(‘fast’);
    }

    function loadData(page){
    loading_show();

    $.ajax
    ({
    type: “POST”,
    url: “the_url_data_page.php”,
    data: “page=”+page,
    success: function(msg)
    {

    $(“#container”).ajaxComplete(function(event, request, settings)
    {

    loading_hide();

    $(“#container”).html(msg);
    });//ajaxComplete

    }//success
    });
    }
    loadData(1); // For first time page load default results
    $(‘#container .pagination li.active’).live(‘click’,function(){
    var page = $(this).attr(‘p’);
    loadData(page);

    });

    $(‘#go_btn’).live(‘click’,function(){
    var page = parseInt($(‘.goto’).val());
    var no_of_pages = parseInt($(‘.total’).attr(‘a’));
    if(page > 0 && page <= no_of_pages){
    loadData(page);
    }else{
    alert('Enter a PAGE between 1 and '+no_of_pages);
    $('.goto').val("").focus();
    return false;
    }

    });

    });

  85. Alexander Mamchenkov
    December 16th, 2011 @ 11:02 am

    Hi,

    I do not really understand what you mean by adding search? What search, where and so on. But i bet you can add a form inside the fancybox thing and do the same AJAX submitions as you do with paging

  86. jose
    December 17th, 2011 @ 9:40 pm

    Yeah something like that. I already have a form i just need to implemented on to the ajax i have try this but did not work.

    and the search SQL is on the same .php file as the data that I’m already retrieving. What i want is that the data will be retrieve automatically but if the search is use it will take over.the problem i’m having is that i get and [search]=undefined of if you can come up with something to get me started.

    Thanks alex for all your help.

    function loadData(page){
    loading_show();
    var search = $(‘input.search’).val();
    $.ajax
    ({
    type: “POST”,
    url: “the_url_data_page.php”,
    data: “page=”+page+”search=”+search,
    success: function(msg)
    {

    $(“#container”).ajaxComplete(function(event, request, settings)
    {

    loading_hide();

    $(“#container”).html(msg);
    });//ajaxComplete

    }//success
    });
    }

  87. Alexander Mamchenkov
    December 18th, 2011 @ 10:06 am

    As I can see, your problem is in “data” param – it should be a json object, not the string, so you would have it like:

    data: {page: page, search: search}

    instead of

    data: “page=” + page + “search=” + search

    Even if string would work (I am not sure), you are missing “&” between page and search, so it should be like:

    data: “page=” + page + “&search” + search

  88. jose
    December 18th, 2011 @ 10:50 am

    thanks again alex for your help. i have added the & and replace the data param i try both but no luck. i don’t know if its with my jquery or my PHP file that the problem is happening. any other suggestions?

  89. Alexander Mamchenkov
    December 18th, 2011 @ 5:07 pm

    If you are getting search to be “undefined” – it is JS problem, since PHP would have it null instead. Make sure that “search” is properly defined. Troubleshoot with console.log or plain alert to see what search you are actually sending to the server.

  90. jose
    December 18th, 2011 @ 8:32 pm

    thanks again i have a question i was working on it I think that the function loadData only displays the page if i add it like this (page, search) it dose not working so i looked at the bottom script and i added the var search = $(‘input.search’).val();
    under var page = $(this).attr(‘p’); then i did the loadData(page, search) still not working i think my problem is their i need to declare a click event on the input below var page = $(this).attr(‘p’); but i will try what you said thanks again.

    function loadData(page){}

    $(‘#container .pagination li.active’).live(‘click’,function(){
    var page = $(this).attr(‘p’);
    loadData(page);
    }

  91. jose
    December 20th, 2011 @ 2:10 pm

    Hey alex thanks for all your help i was able to get it to work.

  92. Alexander Mamchenkov
    December 20th, 2011 @ 3:22 pm

    I am glad you managed to win over it :)

  93. jose
    December 21st, 2011 @ 4:57 am

    Yeah! I have been working on it for a week it was a combination of my PHP file and jquery. I just need a guide on how to that’s what you did thanks again.

  94. sketchgal
    January 17th, 2012 @ 12:30 am

    Genius!!

  95. rosco
    February 21st, 2012 @ 1:57 am

    thank you!!!
    i took hours to solve my problem, thats the first block I saw which solved my problem. I would never ever thought that it’s a time problem.
    Great work!!

  96. Alexander Mamchenkov
    March 14th, 2012 @ 9:54 am

    It really took me a while to figure this out as well.

  97. Geek Blog Post – Get Fancybox to work after Ajax update | Wrecked Magazine – Jason Small
    April 21st, 2012 @ 5:54 am
  98. panos
    June 7th, 2012 @ 7:32 pm

    Hi Alex
    In this site http://www.panosk.cuccfree.org/archive1_final.php
    when load the page, Fancybox work fine. When i click on the year (2012) and after I click in month (the description is in Grecce language) the DIV is refreshed and Fancybox work fine again . The second time when i click again the month the DIV is refreshed BUT Fancybox doesn’t work.I’m trying with your solution but never. Any advice ?

    Thanks

  99. panos
    June 7th, 2012 @ 7:40 pm

    This part of code execute when i click on month and is located in the main page.

    $(‘.l_link’).click(function(){

    $(“#gallery”).load(‘ajaxdiv_final.php?ID=’+this.id,function() { setTimeout(function() {$(‘.al1′).fancybox({
    ‘titlePosition’ : ‘inside’,
    ‘overlayOpacity’ : 0.15

    });},100); }
    );

    );

  100. Alexander Mamchenkov
    June 8th, 2012 @ 8:43 am

    Hi!

    It looks exactly like a problem described in the post. Try wrapping the content of you document ready into setTimeout.

  101. Alexander Mamchenkov
    June 8th, 2012 @ 8:45 am

    I had a problem when 100ms was not enough, though 300 did the job fine.

  102. panos
    June 8th, 2012 @ 2:54 pm

    Hi Alex

    I upgrade my Fancybox version to the latest and all works fine.

    Thanks a lot Alex , have a nice day

  103. Craig
    November 16th, 2012 @ 9:40 pm

    You’re the man Alexander, been battling this for about 24 hours! Thank you!

  104. jasa web desain
    November 25th, 2013 @ 12:59 am

    wow great job…
    This really helpful for me, i was stuck in couple hours just for do this, almost die also :D
    Thx so much..

Leave a Reply





  • Instagram

  • Recent Comments

  • Meta