Home / Open a jQuery Facebox dialog programatically

Open a jQuery Facebox dialog programatically

A few days ago I showed a basic example using the jQuery Facebox plugin to open dialog windows where particular links are made to open in a Facebox dialog. I was then asked in a comment how to open a dialog without making it opened from a link; this is covered with a brief example on the Facebox page but I’ve covered this a little more comprehensively in this post.

Opening a Facebox dialog programatically

It’s really simple and all you need to do is put this in the appropriate section of your code:

$.facebox('Text or HTML here');

If you are loading something via AJAX which will be displayed in the dialog box, then you’ll want the Facebox to appear first showing the loader image so the user knows something is going on. An example of this, and what the commenter was asking about, is loading the results of a login into the dialog window.

Working Example

Here’s a working example of this. The form below doesn’t actually submit anything but waits 3 seconds before loading the final content, to illustrate how the box appears first with the loading image and then to display the actual message.

Login name:

Password:


How the example works

When the button is clicked, a function is called. It opens the Facebox, passing it a function. The function does something (for example attempting to log the user in) and then calls the Facebox function again to render the results of the action.

Here’s the full code from the working example above:

function example_login_facebox() {
    
    $.facebox(function() {
        // do something
        setTimeout(function() {
            $.facebox('Results of login');
        }, 3000);
    });
   
}

And here’s how you might do it making a real AJAX call:

function example_login_facebox() {
   
    $.facebox(function() {
       
        $.ajax({
            data: { 'login' : $('#login').val(), 'password' : $('#password').val() },
            error: function() {
                $.facebox('There was an error when attempting to log you in. Please try again shortly.');
            },
            success: function(data) {
                $.facebox(data);
            },
            type: 'post',
            url: '/path/to/remote/script'
        });
       
    });
   
}

The outer $.facebox call opens up the dialog to display the loading screen. An AJAX call is then done and either renders the Facebox box again either with an error message if there was a problem or the message returned from the AJAX call. You may need to do other stuff too.