A simple Lightbox for jQuery
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.
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':
title
attribute of the link.alt
attribute of the img
tag inside.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:
Gallery With Grouping
Click an item to bring up its lightbox, which will now allow navigation between items.
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.
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):
Gallery With Wrapped Items
Except for the change to the code, this gallery isn't that interesting. Have patience and read on!
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.
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.
Gallery With More HTML
This gallery includes <p>
tags after each link that are turned into
each lightbox's caption, and the third image has two <p>
tags to demonstrate
what happens.
This caption includes a link to Google for no good reason.
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 <p> 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 <p> tag is left alone.</p>
</div>
</div>
$("#pullCaptions .galleryItem").sanebox({
group : 'pullCaptions',
caption : 'next'
});
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).
Gallery With More HTML
This gallery links to large images. The first image is auto-shrunk so that it fits into your browser. The second one is shrunk to a custom size using rel string parameters. The third one uses a set of links to display images sized beforehand.
This image has been auto-shrunk to fit your browser (unless you're browsing with a really big screen).
This is a sequence of images. Notice that the title bar is appended with the link text of the images in the sequence.
(Bigger Zoom) (Biggest Zoom)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.
HTML 5 Video
Try it out! Your browser may not be able to display video encoded as H.264. In this case, you'll either see
a message telling you so (if your browser doesn't support the <video>
tag,
or possibly an 'X' icon (if you're browser doesn't support this codec).
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:
Another Size For This Video
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:
<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.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:
HTML 5 Video with Fallback
Sanebox will try its hardest to get this video to you.
The browser will try one of three HTML5 codecs before defaulting to Flash.
Ogg Version MP4 (H.264) Version Flash BackupIf 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.
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.
Shrinks large images to fit into the browser window. The user can click such images to view them at full size.
Causes videos (Flash or HTML 5) to start as soon as they're loaded.
Specifies where the lightbox should get its caption from, and how that caption should be displayed.
Specifies whether or not the lightbox should have a clickable close box in its title bar.
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.
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.
Specifies whether or not elements that are inside the gallery item should be hidden if they are used as the lightbox's title.
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.
Specifies how the lightbox should display a title bar, and where it should get the html that goes into the title bar.
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:
open
is triggered.load
is triggered on the Sanebox that was clicked.unload
is triggered on the first item when the user navigates through the gallery.load
is triggered on the next item that is called up.unload
and load
for every item in the Sanebox
that the user navigates to.unload
is called on the currently displayed item when the user exists the Sanebox.close
is triggered.
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.
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.
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.
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.
Methods are called by calling the Sanebox plugin using jQuery.
$().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.
Each key is a Sanebox option, and its value is the new default for that option.
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'
});
$(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.
A jQuery selector. The matched items will be canceled.
The following example removes Sanebox functionality for all elements with a class of "lightbox."
$(".lightbox").sanebox("cancel");
An array of Strings. Each index should be the name of one Sanebox group that should be removed.
The following example removes Sanebox functionality for two groups called "calvin" and "hobbes":
$(".lightbox").sanebox("cancel", ["calvin, "hobbes"]);
The ID of one Sanebox to cancel.
The following example removes Sanebox with the id "moe":
$().sanebox("cancel", "moe");
$(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.
A jQuery selector. The first element in the matched set will be opened in a new Sanebox .
The following example opens the first link on the page with a class of "lightbox" into a new Sanebox:
$("a.lightbox").sanebox("open");
The ID of one Sanebox to open.
The following example opens the Sanebox with the id "susie":
$(").sanebox("open", "susie");
$(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.
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.
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");
The ID of one Sanebox to get.
The following example assigns the Sanebox with the id "wormwood" to the variable
theItem
:
var theItem = $().sanebox("get", "wormwood");
$().sanebox("close");
Closes any Sanebox windows that are currently open.