how to check if fancybox exists on page already

Viewed 16714

I am trying to check if a fancybox has been loaded already. If so then I run an ajax script to put content inside.

If not I open a fancybox iframe and it fetches content.

Here is the code:

if ($('div#fancybox-frame:empty').length >0) { 
    alert('it is empty');

$.fancybox({
   'width': '80%',
    'height': '80%',
    'autoScale': true,
    'transitionIn': 'fade',
    'transitionOut': 'fade',   
    'type': 'iframe', 
    'href': '/show_photo'
});
 }
 else{
    alert('it is full');   
    $.ajax({
        type: "GET",
        url: "/show_photo",
        success: function(data){
        cropping_arrived();
        }
    });
  }
});

It always returns that it is full even when I know there is not fancybox open.

Any ideas?

6 Answers

I made it work with below code:

if(typeof $.fancybox == 'function') {
     fancy box loaded;
} else {
     fancy box not loaded;
}

In my case for ending up here in this thread, I had a script checking if user input had been detected through mouse movement or keyboard activity. However the parent page were not detecting activity when being inside a fancybox iframe.

To adjust and compensate for this fact, I let the script running in the background know if there is an open iframe in the DOM (as I am not using iframes besides with fancybox) by using the following code:

if ($('body iframe').length > 0)
{
    console.log('Fancybox Open');
}
else
{
    console.log('Fancybox NOT Open');
}

You could also choose to have your iframe content have a specific ID or Class that you measure, however take in mind that when the HTML element is dynamically instigated you have to target an existing parent selector first which were present at DOM to be able to find your newly created element.

A bit late, but this works for Fancybox (v4):

/// grab the top fancybox slide element:
    
var is_fancybox_open = document.getElementById("fancybox-1");
    
if(is_fancybox_open === null)
{
            
    var fancybox_id = new Fancybox([
        {
            width: 500,
            height: 400,
            ...etc...
        },
    ]);
}
Related