Open a jQuery Facebox on page load

I was asked this morning how to go about opening a jQuery Facebox when the page loads; while I normally find dialogs that open in this way somewhat annoying they do have their uses when trying to show some form of disclaimer. This post shows how to do this.

Download Facebox

Download the Facebox plugin and associated files from http://defunkt.io/facebox/ There are a number of examples on that page but here I present a full HTML skeleton for you to start with.

Download jQuery from http://jquery.com/

Working example

View the working example here. This opens a new page and as soon as it’s loaded the jQuery Facebox dialog will be displayed without any user intervention.

The code

Here’s the full HTML and Javascript required to achieve this. Obviously you need to subsitute the Javascript and CSS url locations to where you have these located.

<!DOCTYPE html> 
<html>
<head>
<title>Facebox on load</title>
<link rel="stylesheet" href="/facebox/facebox.css" />
<script src="/js/jquery-1.4.2.min.js"></script>
<script src="/facebox/facebox.js"></script>
<script>
$(document).ready(function() { 
.facebox.settings.opacity = 0.5; 
$.facebox('This will display after the page has finished loading');
});
</script>
 
</head>
<body>
 
</body>
</html>

After the page loads, the dialog will display with the text “This will display after the page has finished loading”.

Getting the content via an Ajax request

To get the content from an Ajax request instead of it being hard coded into the HTML/JS, change this line:

$.facebox('This will display after the page has finished loading');

to this, changing the /path/to/remote.html to the URL of your content:

$.get('/path/to/remote.html', function(html) {
 $.facebox(html);
 })