Sanebox

A simple Lightbox for jQuery

Documentation

My primary goal when making Sanebox was to make it do what I wanted and not much else. I wanted it to be a useful, friendly jQuery plugin. My secondary goal was making it easy for anybody to use, and this docuentation should help with that. We'll get going with a simple example that will satisfy 75% of Sanebox's users, and the next example will probably be enough for another 24%. The remaining 1% can have fun with what's left.

Contents

  1. Basic Usage
  2. Grouping Lightboxes
  3. Getting Fancier (and more complex): Captions and Titles
  4. Making Captions Out of Elements
  5. Zooming Images
  6. HTML 5 Video
  7. Rel Strings
  8. Alternative Sources For Videos
  9. A Little Note On Video Formats
  10. Reference
    1. Options
    2. Callbacks
    3. Methods

Basic Usage

A lightbox is initialized by executing the jQuery sanebox() method. This usually happens during a page's $(document).ready() function, but can be done anytime:

$(document).ready(function () {
	$("a.lightbox").sanebox();
});

The code uses jQuery to select all links on the current page with a class of 'lightbox', then makes it so that clicking them brings up their target (the href attribute) in a lightbox:

The code for each element above is pretty straighforward:

<a class="lightbox" href="images/rocks.jpg" title="Sample Lightbox"><img src="images/rocks_th.jpg" alt="Test Screen 1" alt="This is a test caption."/></a>
<a class="lightbox" href="images/safeco.jpg" title="Another Sample Lightbox"><img src="images/safeco_th.jpg" alt="This is a test caption."/></a>

As you can see, you get a lot of functionality 'right out of the box':

Grouping

It's convenient to allow your visitors to browse through the lightbox objects on your page without having to click on a thumbnail, view the image or video, close the lightbox, and then click on the next thumbnail, close that lightbox, click on the third one… and so on. Sanebox allows you to group lightboxes into a Gallery of items. All that is required is a small change to the code:

$(document).ready(function () {
	$(".lightboxWithGroup").sanebox({
		group : 'groupName'
	});
});

The above code yield the following behavior for the gallery below:

There is no change to the HTML used to generate the links, aside from the different class name:

<a class="lightboxWithGroup" href="images/rocks.jpg" title="Sample Lightbox"><img src="images/rocks_th.jpg" alt="Test Screen 1" alt="This is a test caption."/></a>
<a class="lightboxWithGroup" href="images/safeco.jpg" title="Another Sample Lightbox"><img src="images/safeco_th.jpg" alt="This is a test caption."/></a>
<a class="lightboxWithGroup" href="audio.flv" title="Flash Video"><img src="audio_flv_th.png" alt="This is a Flash video."/></a>

Notice that the item you click on is opened within the gallery at the correct position. Within a group, the user can use the left / right arrow keys to navigate.

Getting Fancier (and more complex): Captions and Titles

Sanebox also supports a few other options, including HTML 5 video and pulling captions or titles from elements on the page (instead of attributes of the links). These options are a bit more complex and require a bit more markup, but they can make your lightbox displays more 'backward-compatible' with browsers that do not support JavaScript.

The following options use extra HTML elements. Since it would be confusing to place extra elements inside your <a> tags, The first thing you must do is wrap your links in a <div> tag (actually, any block-level HTML element will do). This allows us to logically 'group' elements that are related. It also makes it easier to style the links or thumbnails. Here is the HTML markup and the jQuery code:

<div id="#wrappedGallery">
	<div class="galleryItem" title="Title Is Now">
		<a href="images/rocks.jpg" title="Sample Lightbox"><img src="images/rocks_th.jpg" alt="Test Screen 1" alt="This is a test caption."/></a>
	</div>
	<div class="galleryItem" title="Pulled From the div">
		<a href="images/safeco.jpg" title="Another Sample Lightbox"><img src="images/safeco_th.jpg" alt="This is a test caption."/></a>
	</div>
	<div class="galleryItem" title="(Not the anchor)">
		<a href="audio.flv" title="Flash Video"><img src="audio_flv_th.png" alt="This is a Flash video."/></a>
	</div>
</div>
$(document).ready(function () {
		$("#wrappedGallery .galleryItem").sanebox({
			group : 'wrapped'
		});
});

The above code results in the following gallery and behavior, which hasn't changed much (yet):

One thing to note is that wrapped items by default pull their title from the title attribute of the wrapping div, not the link itself. The caption, coming from an alt attribute, is still attached to the image.

Making Captions Out of Elements

Now we can actually do something with the wrapped divs. In this example, we tell Sanebox that we want the gallery items to pull their captions from the very next element after the link in the div that contains them. Sanebox then hides these elements on the page, so the gallery isn't cluttered and redundant information is not displayed twice.

Now, if JavaScript is not supported in your visitor's browser, they will see the caption underneath the image for each gallery item. An additional benefit is that captions can include any type of HTML you like — links, images, and so on.

We achieve this by adding a new option to our jQuery call, in addition to the group option we've already seen: caption. This option tells the sanebox plugin where to find the caption for each lightbox it creates. Captions can be pulled from several places: the title of the wrapping element, the title of the image, the alt attribute of an image inside the link (which is the default behavior), the next element after the link tag, any bit of text, or even some other HTML element inside the wrapped div that you select with another jQuery selector. It gives you a lot of flexibility to set up your HTML how you want, then configure sanebox to fit that layout.

Note that most other HTML inside the wrapper (after the element that is pulled to make the caption) is ignored when the lightbox is initialized. The exception is when you provide alternative images or videos, which we will discuss below.

It's also possible to do this with titles, which support most of the same options as captions.

Here is the HTML and JavaScript that makes this possible:

<div class="gallery" id="pullCaptions">
<div class="galleryItem" title="Item 1">
<a href="images/rocks.jpg"><img src="images/rocks_th.jpg"/></a>
<p>This caption came from a &lt;p&gt; element.</p>
</div>
<div class="galleryItem" title="Item 2">
<a href="images/safeco.jpg"><img src="images/safeco_th.jpg"/></a>
<p>This caption includes a <a href="http://www.google.com">link to Google</a> for no good reason.</p>
</div>
<div class="galleryItem" title="Flash Video (Next We'll do HTML 5)">
<a href="audio.flv"><img src="audio_flv_th.png"/></a>
<p>Couldn't think of anything to put in this caption, except <strong>gratuitous</strong>
HTML <span style="color: yellow">formatting.</span></p>
<p>This &lt;p&gt; tag is left alone.</p>
</div>
</div>
$("#pullCaptions .galleryItem").sanebox({
	group : 'pullCaptions',
	caption : 'next'
});

Zooming Images

Because the images you want to link to are often much bigger than a browser window, Sanebox has a few ways to resize them.

By default, if you link to an image that is larger than the user's window, it will be automatically shrunk inside the Sanebox. This is a configurable option called autoshrink, and you set it to either true or false (without quotes) inside your Sanebox's initializiation call. Once the image is displayed shrunk, the user can click on it inside the Sanebox to zoom it to full size. This is indicated by the cursor changing into a magnifying glass () when the user hovers over the image.

The second way to re-size an image inside a Sanebox is to use rel string parameters. These are defined in the rel attribute of the a tag that links to the full-size image. They are made up of key=value pairs, each one separated by a single semicolon (;).

The third way is to explicitly define each zoomed size using a series of a tags inside a wrapped div. The Sanebox will display the image linked to in the first a tag, then display the next one when the user clicks on it, then the next one, and so on. It then wraps around to the first one once the user clicks on the last image. This allows you to scale the images yourself, which often looks smoother than the in-browser scaling the other methods use. All you have to do is add rel="alternative" to the subsequent images in the sequence (but not the first).

HTML 5 Video

Sanebox also supports the native HTML 5 video format, and includes tools that allow you to fall back to Flash if the user's browser doesn't support any video type that you supply. My goal when adding this support was to make this as simple and intuitive for your site's users as possible. Unfortunately, this means that it's a bit more complicated for you. Whether or not it's worth it is up to you. You can always just stick with Flash video. The easiest way to include an HTML 5 video is shown below. Bear in mind that this is just one video, with no fallback, so it may not play in your browser (it opens in FireFox for me). Web video is a complicated, evolving topic. If your browser does not support playback of Ogg/Theora video natively, then you will see the message that is displayed informing users that the video is unavailable.

Sizing Videos

As with images, you can specify a custom size for a video using rel string parameters. This works for either Flash or HTML 5 videos. By default, videos are displayed at 400 by 300 pixels. If your video is a different size, you must specify its width and height using rel string parameters. The following Gallery with an HTML 5 video demostrates a video at a custom size:

<a href="asteroids.flv" rel="width=640;height=480" title="Flash video with a custom size."><img src="spaceroids_flv_th.jpg" alt="This video MAY show up... it's complicated." /></a>

You can override any group parameter (such as caption or title source) for an item using the rel parameters.

This markup would produce a gallery like this:

Alternative Sources For Videos

Like many things web-related, cross-browser issues involving the <video> tag (which is used to play HTML 5 video) is a nightmare. Luckily, HTML 5 allows a video to have more than one source, each one pointing to the same copy of a video in a different file format. Sanebox supports this, too. You can even fall back to Flash video (in case the visitor's browser supports none of the video formats you try to use.

To incorporate these sources into a Sanebox gallery, just follow these steps:

  1. Create the hyperlink to the video as you normally would, and make sure it's wrapped up in a <div> or another element. In order to use alternate sources, you must use wrapped gallery items. This hyperlink should point to your preferred video file format. It can be anything but a Flash video.
  2. Add a hyperlink for each alternate video inside the gallery item wrapper. If you are using the 'next' option for captions or titles, these alternate links would go after the caption/title elements.
  3. You can also add specific information about the video format for each video (type and codec) to the rel parameters of each alternate source. See a guide to HTML 5 video for more information. You don't need to worry about this step, it just allows you to optimize your bandwidth by letting vistors' browsers decided if they will play a video before downloading it.
  4. You can optionally add one optional link to Flash video to fall back to. This will always be the last resort, meaning you can't expect the Flash video to have higher precedence than an ogg/theora or H.264 video.

The browser will first try the video you link to directly, in the first <a> tag. If that fails, then it will try the next video you linked, and so on. Finally, if none of the videos work, then the fallback Flash video will be displayed. This will all be seamless to your visitor.

I would suggest that you set the link text of these alternate sources to descriptions of the file format — remember, they will show up in browsers that don't support JavaScript. This is another way to fall back.

Here is an example of a video that should play on your browser, no matter what:

A Little Note On Video Formats

If you're going to the trouble of making four encodings of each video you want to show (H.264, Ogg/Theora, and VP8 for HTML 5 and then a Flash version, too), I suggest putting some thought into the order you list the alternative. H.264 is unfortunately encumbered by patents, meaning it's not a truly free format. I would suggest using Ogg/Theora or VP8, which are not encumbered, then having H.264 as a fallback option. This way you can serve us the video in a free manner, then fall back to the less-free alternative if you have to.

And It Goes On…

That's the introductory tutorial and basic usage information for Sanebox. There's a lot more you can do, but to utilize it you have to have some familiarity with jQuery and JavaScript.

Options Reference

autoshrink

Type
Boolean
Default
true

Shrinks large images to fit into the browser window. The user can click such images to view them at full size.

Values
true
Images that are too large to fit into the window are shrunk.
false
Elements are not shrunk.

autostart

Type
Boolean
Default
false

Causes videos (Flash or HTML 5) to start as soon as they're loaded.

Values
true
Videos will start as soon as they're ready.
false
The user must click the 'play' button to start a video.

caption

Type
String, Selector String
Default
next

Specifies where the lightbox should get its caption from, and how that caption should be displayed.

Values
'next'
The very next element inside the lightbox element will be used as the caption. If consumeCaption is set to true, the caption will be hidden on the page.
'title'
Pulls the content of the caption from the matched element's title attribute. Use this when you wrap the media link inside a div.
'link'
Pulls the content of the caption from the first link tag's title attribute.
'none'
No caption will appear for this lightbox.
Selector String
The first element inside the matched item that matches the given selector will be inserted into the caption. If consumeCaption is true, then the element will also be hidden from the page.
String
The value of the given string will be used as the element's caption.
See Also

closebox

Type
Boolean
Default
true

Specifies whether or not the lightbox should have a clickable close box in its title bar.

Values
true
The lightbox will have a clickable close box.
false
The lightbox will not have a clickable close box.

controls

Type
Boolean
Default
true

Controls whether or not Flash and HTML 5 videos display with a control bar along the bottom of the video. This is a useful setting if you want to implement your own HTML 5 controls, for example.

Values
true
Videos will display with a control bar.
false
Videos will not play with a control bar. Note that unless you implement your own controls, setting autostart to false is a bad idea.

consumeCaption

Type
Boolean
Default
true

Specifies whether or not elements that are inside the gallery item should be hidden if they are used as the source of the lightbox's caption.

Values
true
The element will be hidden on the page.
false
The element will be used as the caption but will remain on the page.

consumeTitle

Type
Boolean
Default
true

Specifies whether or not elements that are inside the gallery item should be hidden if they are used as the lightbox's title.

Values
true
The element will be hidden on the page.
false
The element will be used as the title but will remain on the page.

group

Type
String, Boolean
Default
true

Determines which gallery group the lightbox should be a part of, if any. Gallery groups are an assortment of links bound together with options to navigate between them.

Values
true
The default group, which doesn't have a name. This is a catch-all for any items that are added without a group.
false
The item will not be part of a group, it will be displayed on its own.
String
If a string is specified, then the gallery items will be made a part of the gallery group with that name.
See Also

title

Type
String, Selector String
Default
title

Specifies how the lightbox should display a title bar, and where it should get the html that goes into the title bar.

Values
'title'
Pulls the content of the title bar from the matched element's title attribute. Use this when you wrap the media link inside a div. If no attribute is found, the titlebar will be displayed, but will be blank.
'link'
Pulls the content of the title bar from the first link tag's title attribute. If no attribute is found, the title bar will be displayed, but will be blank.
'none'
No title bar will appear for this lightbox.
Selector String
The first element inside the matched item that matches the given selector will be inserted into the title bar. If no matching element is found, the title bar will be displayed, but will be blank.
String
The value of the given string will be used as the element's title.
See Also

Callbacks

You can provide function callbacks to the Sanebox initializer. These are triggered when various actions are taken by the user. Here is the sequence of callbacks that are triggered when a sanebox is opened, navigated, then closed:

  1. open is triggered.
  2. load is triggered on the Sanebox that was clicked.
  3. unload is triggered on the first item when the user navigates through the gallery.
  4. load is triggered on the next item that is called up.
  5. Repeat unload and load for every item in the Sanebox that the user navigates to.
  6. unload is called on the currently displayed item when the user exists the Sanebox.
  7. close is triggered.

open

Type
Function, Boolean
Default
false

This function is called on the lightbox after it is loaded and displayed. It is called each time a lightbox is brought up, but not when navigating between items in a gallery (that's the load() callback). The this variable will reference the lightbox.

Parameters
source
The html element that triggered the lightbox.
group
The group object that the element belongs to.

load

Type
Function, Boolean
Default
false

This function is called on a lightbox after a media item is displayed. It is called each time a new media item is displayed. That means that every time 'next' or 'prev' is clicked, it is called. The this variable will reference the lightbox.

Parameters
source
The html link element that triggers the lightbox.
group
The group object that the element belongs to.

unload

Type
Function, Boolean
Default
false

This function is called on a lightbox right before it is unloaded. It is called each time a new media item is displayed. That means that every time 'next' or 'prev' is clicked, it is called. The this variable will reference the lightbox.

When navigating in a gallery, the unload() event is called on the current lightbox, then the load() event is called on the new lightbox.

Parameters
source
The html link element that is about to disappear.
group
The group object that the element belongs to.

close

Type
Function, Boolean
Default
false

This function is called on a lightbox right before it is closed and the page returns to normal. The this pointer points to the lightbox element.

Parameters
source
The currently-displayed lightbox.
group
The group object that the element belongs to.

Methods

Methods are called by calling the Sanebox plugin using jQuery.

defaults

$().sanebox("defaults", options)

Sets (and overrides) the default options for Sanebox. Sanebox has default values for all its parameters (as listed above), and calling the defaults method allows you to change these defaults for all subsequent Sanebox calls.

Parameters
options
type
Map

Each key is a Sanebox option, and its value is the new default for that option.

Example

The following example makes it so that every subsequent call to Sanebox will result in lightboxes having their captions pulled from the link's title attribute instead of the alt attribute.

$().sanebox("defaults", {
	caption : 'link'
});

cancel

$(selector).sanebox("cancel");
$().sanebox("cancel", groups);
$().sanebox("cancel", id);

Disables Sanebox functionality on the specified items. You can either use jQuery to select the items you want to disable, or specify a list of groups to disable, or specify the ID of a certain gallery item to disable. This is useful if you have many calls to the Sanebox initialization function that share many configuration options.

Parameters
selector
type
Selector

A jQuery selector. The matched items will be canceled.

Example

The following example removes Sanebox functionality for all elements with a class of "lightbox."

$(".lightbox").sanebox("cancel");
groups
type
Array

An array of Strings. Each index should be the name of one Sanebox group that should be removed.

Example

The following example removes Sanebox functionality for two groups called "calvin" and "hobbes":

$(".lightbox").sanebox("cancel", ["calvin, "hobbes"]);
id
type
String

The ID of one Sanebox to cancel.

Example

The following example removes Sanebox with the id "moe":

$().sanebox("cancel", "moe");

open

$(selector).sanebox("open");
$().sanebox("open", id);

Open a Sanebox for the specified item. This can be done in one of two ways. The first is to supply a jQuery selector; in this case, the first element in the document that matches the selector will be opened as a Sanebox. The second way is to supply the ID of one Sanebox item; in this case that item will be opened in a new Sanebox. Note that this method doesn't initialize an anchor or div as a Sanebox, it merely opens a Sanebox that has already been set up.

Parameters
selector
type
Selector

A jQuery selector. The first element in the matched set will be opened in a new Sanebox .

Example

The following example opens the first link on the page with a class of "lightbox" into a new Sanebox:

$("a.lightbox").sanebox("open");
id
type
String

The ID of one Sanebox to open.

Example

The following example opens the Sanebox with the id "susie":

$(").sanebox("open", "susie");

get

$(selector).sanebox("get");
$().sanebox("get", id);

Returns the internal GalleryItem object that Sanebox uses for the specified element or elements. PLease refer to the source code for more information about the GalleryItem class.

Parameters
selector
type
Selector

A jQuery selector. Any GalleryItems associated with the matching elements will be returned. If only one matches, it will be returned alone; otherwise, an array of all matching GalleryItems will be returned.

Example

The following code gets all GalleryItems on the page that were created from a tags with the class lightbox, and assigns them to the variable theItem:

var theItem = $("a.lightbox").sanebox("get");
id
type
String

The ID of one Sanebox to get.

Example

The following example assigns the Sanebox with the id "wormwood" to the variable theItem:

var theItem = $().sanebox("get", "wormwood");

close

$().sanebox("close");

Closes any Sanebox windows that are currently open.