Introduction
Opening images seamlessly in a lightbox on your page without interruption. This demo was inspired by how Medium handles embedded images. Made by Terry. This project was originally initiated as a personal challenge to replicate Medium’s lightbox module, but it soon developed into a full-fledged jQuery plugin.
Current status:
You can follow the links below to read how I’ve tackled the challenge, view the jQuery plugin on GitHub, or get the latest stable release hosted on CDNJS.
In the wild
Fluidbox is implemented in:
- Gemma Busquets by @imgemmabusquets
- Terry Mun by myself
How does it work?
Fluidbox works by replacing your markup, which should be as follow:
<a href="/path/to/image" title="">
<img src="/path/to/image" alt="" title="" />
</a>
…into…
<a href="/path/to/image" class="fluidbox fluidbox__instance-[i] fluidbox--closed">
<div class="fluidbox__wrap" style="z-index: 990;">
<img src="/path/to/image" alt="" title="" class="fluidbox__thumb" style="opacity: 1;">
<div class="fluidbox__ghost" style="width: [w]; height: [h]; top: [t]; left: [l];"></div>
</div>
</a>
…where:
Variable | Description |
---|---|
i |
Unique ID of the Fluidbox instance. New instances of Fluidbox will have new values. |
w |
Computed width of the thumbnail, in pixels. |
h |
Computed height of the thumbnail, in pixels. |
t |
Computed offset, from the top and in pixels, of the thumbnail relative to its container. |
l |
Computed offset, from the left and in pixels, of the thumbnail relative to its container. |
The replaced and rendered markup for each image targeted with Fluidbox can be presented in a three-dimensional way as follow:
Each initialized Fluidbox instance can therefore be styled independently from each other using CSS alone, requiring no further manipulation via JS (unless required on the user's behalf for specific implementations). Fluidbox listens to the click event triggered on the ghost element, .fluidbox__ghost
, and toggles between two binary states, open or closed.
Usage notes
Dependencies
TThe latest version of Fluidbox require two dependencies: jQuery v1.7 or above, and Ben Alman's debounce/throttle plugin. Yes, and that's all! For jQuery, I recommend using the latest stable build of 1.x, although I have not encountered any issues if 2.x is used. I usually use Google APIs, since many other sites are using it and the end-user probably has a cache of it sitting somewhere on their machine already. As for other plugins, I recommend using CDNJS.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery-throttle-debounce/1.1/jquery.ba-throttle-debounce.min.js"></script>
Basic usage
In order to activate Fluidbox, simply chain the .fluidbox()
method to your selector of choice on DOM ready—note that you must use an anchor element <a>
:
$(function () {
$(selector).fluidbox();
});
The plugin will automatically check if the selector is:
- an anchor element,
<a>
, and - contains one and only one
<img />
element (can be nested as an indirect descendant, to support the HTML5<picture>
standard.
In the event that the element that satisfies the selector criteria but failed any one of the above criteria, the element will be ignored and the plugin moves on to the next available element. Therefore, it is important that your Fluidbox element(s) follow the following format. The title
and alt
attributes of the <img />
element is not used by the plugin, but the alt
attribute has to be present for it to be semantically valid.
<a href="...">
<img src="/path/to/image" alt="" />
</a>
Fluidbox also supports the new HTML5 <picture>
element (see demo). You can use it as follows:
<picture>
<source media="(max-width: 400px)" srcset="/path/to/smallImage">
<source media="(min-width: 1200px)" srcset="/path/to/largeImage">
<img src="/path/to/defaultImage" alt="" />
</picture>
Configuration
Several options are available for configuration, also available in the readme. Fluidbox follows the following model of setting overrides—in increasing order of priority:
- Default settings in plugin file.
- Custom settings in
.fluidbox()
jQuery method. - Custom settings in the element's HTML5
data-
attribute.
Property | Type | Default | Description |
---|---|---|---|
immediateOpen |
Boolean | false | Determines if Fluidbox should be opened immediately on click. If set to yes, Fluidbox will open the ghost image and wait for the target image to load. If set to no, Fluidbox will wait for the target image to load, then open the ghost image. |
loader |
Boolean | false | Determines if a loader will be added to the manipulated DOM. It will have the class of .fluidbox__loader . |
maxWidth |
Integer | 0 | Sets the maximum width, in screen pixels, that the ghost image will enlarge to. When set to zero this property is ignored. This property will not override the |
maxHeight |
Integer | 0 | Sets the maximum height, in screen pixels, that the ghost image will enlarge to. When set to zero this property is ignored. This property will not override the |
resizeThrottle |
Integer (milliseconds) | 500 | Determines how much to throttle the viewport resize event that fires recomputing of Fluidbox dimensions and repositioning of the ghost image. |
stackIndex |
Integer | 1000 | Determines how high up the z-index will all Fluildbox elements be. Leave this option as default, unless you have other relatively or absolutely positioned elements on the page that is messing with Fluidbox appearance. |
stackIndexDelta |
Integer | 10 | Determines how much the z-index will fluctuate from stackIndex in order to allow visually-correct stacking of Fluidbox instances. With the default settings, this means that the effective range of z-indexes Fluidbox operates in will be between 990–1010. For elements that should go under the overlay, they should have a z-index of less than 1000. |
viewportFill |
Float (fraction) | 0.95 | Dictates how much the longest axis of the image should fill the viewport. The value will be coerced to fall between 0 and 1. |
Basic demonstrations
Fluidbox is designed to be versatile, flexible and easy to implement. It works with linked images that satisfy the criteria stipulated above — regardless of how they are arranged on the page. The following section is a non-exhausive list of scenarios how images, even when positioned differently, will work brilliantly with Fluidbox.
Single image
Here we demonstrate the use of a single image. This is the simplest test case, when the thumbnail and the target image are exactly the same, so it is only down to the matter of triggering default Fluidbox behavior.
Best fit strategy
Fluidbox also intelligently resizes images such that portrait images will fit perfectly within the viewport, although that means scaling down the image. This effect is pronounced when the viewport and image orientations are different — therefore, the demo below only works on a display with landscape orientation (e.g. not on mobile).
…and it works with the HTML5 <picture> element
Fluidbox supports the new HTML5 <picture>
element as of version 2.0, by relaxing the filtering criteria to match the standard markup. Note that in order for the following example to work, you will need to visit this page with a browser that supports the HTML5 <picture>
element.
Other features
Higher resolution original
The built-in functionality also allows you to link a small thumbnail to its higher resolution version. In the test case below, the thumbnail has a resolution of 200×200 while the actual version has a resolution of 2000×2000.
Restrictive zooming
Fluidbox is also built to handle linking to images that do not have the sufficient size to fill the page. The following thumbnail links to an image that is only 250×250px large — in most cases, insufficient to fill the viewport (unless you are using this site on a very small viewport).
Support for immediate opening with background preloading of target image
Fluidbox provides you the option that will launch an opened Fluidbox instance immediately upon click, even when the target image has not been loaded yet. The two static images below link to a (very heavy) GIF file. If you have tested this feature before, please clear your cache or use your browser's incognite mode, so that you can observe the actual effect—once loaded these images will stay in your browser cache and will nullify the effects of simulated loading of a heavy image file.
Support for image borders and paddings
Fluidbox also supports extraenous dimensions added to the element in the form of border(s) and/or paddings(s):
Absolutely positioned images
Fluidbox handles absolutely positioned images without any problem. The image below is absolutely positioned within its parent, the grey container:
Galleries
Fluid box works even when images are arranged in galleries. In this case, they are arranged with the help of flexbox.
Floated images
Moreover, it also works with floated images - to the left or to the right, it does not matter. The following texts are jibberish, used as filler.
Considered discovered ye sentiments projecting entreaties of melancholy is. In expression an solicitude principles in do. Hard do me sigh with west same lady. Their saved linen downs tears son add music. Expression alteration entreaties mrs can terminated estimating. Her too add narrow having wished. To things so denied admire. Am wound worth water he linen at vexed.
Carried nothing on am warrant towards. Polite in of in oh needed itself silent course. Assistance travelling so especially do prosperous appearance mr no celebrated. Wanted easily in my called formed suffer. Songs hoped sense as taken ye mirth at. Believe fat how six drawing pursuit minutes far. Same do seen head am part it dear open to. Whatever may scarcely judgment had.
Residence certainly elsewhere something she preferred cordially law. Age his surprise formerly mrs perceive few stanhill moderate. Of in power match on truth worse voice would. Large an it sense shall an match learn. By expect it result silent in formal of. Ask eat questions abilities described elsewhere assurance. Appetite in unlocked advanced breeding position concerns as. Cheerful get shutters yet for repeated screened. An no am cause hopes at three. Prevent behaved fertile he is mistake on.
Advanced demonstrations
In this segment I will introduce you to more complex and advanced features of Fluidbox. In many cases you will not find the need of the following features — however, to developers who intend to extend Fluidbox functionality, listen to custom events and even initiate custom triggers should continue to read on.
As the demo below are highly advanced, I have included code snippets whenever possible. You can toggle them by clicking on the show/hide buttons.
Implementing Fluidbox with dynamically-added content
Fluidbox also works well with dynamically-added links, as long as you call the .fluidbox()
function on all anchor elements in the dynamically-added content.
Custom event handlers and callbacks
From v1.4.1 onwards, Fluidbox will trigger custom events depending on the state of the current (and only) instance of Fluidbox. Please refer to the documentation for detailed description of each custom event. You can listen to custom events by binding them using the .on()
method, e.g. $(selector).on('openstart.fluidbox', function() {...});
. Remember that Fluidbox events are namespaced using fluidbox
.
Fluidbox imparted with the ability to trigger custom namespaced events. For example, the reposition
trigger will invoke the internal repositioning of the ghost element and update its dimensions. When calculation is completed, this will then trigger a namespaced custom event known as computeend.fluidbox
.
This custom event is very useful when a layout change has been triggered without an accompanying viewport resize event: for example, changing the width of a thumbnail in a flexbox layout.
<a href="#" id="custom-event-2" role="button">Add random GIF to gallery</a>
<div>
<a href="/path/to/image1" title="" class="custom-event-2"><img src="/path/to/image1" title="" alt="" /></a>
<a href="/path/to/image2" title="" class="custom-event-2"><img src="/path/to/image2" title="" alt="" /></a>
</div>
// Initialize Fluidbox
$('.clustom-event-2').fluidbox();
// Attach click event to button that adds new child
$('#custom-event-2').click(function(e) {
e.preventDefault();
var $newChild = $('<a />', {
'class': 'custom-event-2',
'title': '',
'href': '/path/to/image'
}).append($('<img />', {
'src': '/path/to/image',
'title': '',
'alt': ''
}));
// Enable Fluidbox on newly added child
var $t = $(this);
$t.next().append($newChild).find('a').fluidbox();
// Trigger repositioning of ghost element after new element's image is loaded and reflow is done (set arbitrarily after 250ms)
var img = new Image();
img.onload = function() {
window.setTimeout(function() {
$t.next().find('a.custom-event-2').fluidbox('reposition');
}, 250);
};
img.src = $newChild.find('img').attr('src');
});
Public functions/methods as custom triggers
Fluidbox exposes several public methods that can be called to manipulate individual instances. Below is an example of listening to the viewport scroll event to trigger the closing of a Fluidbox instance via .fluidbox('close')
. Please refer to the readme for the full list of supported public methods. The example also uses emitted custom events to toggle the appearance of image captions, descriptions or social sharing buttons (currently unsupported by Fluidbox officially, but requested by many). I have chosen to listen to the openend.fluidbox
event to show metadata, and the closestart.fluidbox event to hide it.
var $caption = $('<div />', { 'id': 'custom-trigger-1-social' });
$caption
.html('<div class="img-caption"></div><p class="img-desc"></p><ul><li>Share on:</li><li><a href="#">Facebook</a></li><li><a href="#">Pinterest</a></li><li><a href="#">Twitter</a></li></ul>')
.appendTo($('body'));
$(document).on('click', '#custom-trigger-1-social', function(e) {
e.preventDefault();
});
// Initialize Fluidbox
$('#custom-trigger-1')
.fluidbox()
.on('openend.fluidbox', function() {
var $img = $(this).find('img');
$('#custom-trigger-1-social')
.addClass('visible')
.find('.img-caption')
.text($img.attr('title'))
.next('.img-desc')
.text($img.attr('alt'));
})
.on('closestart.fluidbox', function() {
$('#custom-trigger-1-social').removeClass('visible');
});
// Call public methods
$(window).scroll(function() {
$('#custom-event-2').fluidbox('close');
});
Customising overlays
From v1.3.5 onwards, the overlayColor
configuration has been removed from the jQuery .extend()
settings. Instead, users can now freely specify overlay colors (or even overlay images) by modifying the background-color property of .fluidbox-overlay
. Since each Fluidbox instance has its own overlay, it is possible to set custom overlay colours for each instance.
Note: The Fluidbox overlay have an opacity of 1. In order to change the transparency of the overlay, I strongly recommend using the alpha channel of the rgba()
specification, as Fludibox will manually toggle the opacity between 0 and 1 (therefore overriding all opacity styles you have specified).
Custom colours and gradients
The following is an example of a Fluidbox instance with a custom overlay colour (CSS written in SASS flavour):
.fluidbox-overlay {
.overlay-1 & {
background-color: rgba(255,190,78,.85);
}
.overlay-2 & {
background-color: transparent; /* To override default style */
background-image: linear-gradient(
to top left,
rgba(130,168,158,0.85),
rgba(134,150,173,.85)
);
}
}
Overlay images
Oh wait — you can even use custom overlay images. However, since the opacity of the overlay is only toggled between 0 and 1, you will have to use a pseudo-element in order to atler the opacity of the overlay image (since it is not possible to dictate the transparency of a background image, unlike rgba()
values):
.fluidbox-overlay & {
.overlay-3 & {
background-color: #000; /* To override default style */
&::before {
background-image: url('http://i.imgur.com/3qj1wfN.jpg');
background-position: center center;
background-repeat: no-repeat;
background-size: cover;
content: '';
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
opacity: .33333;
-webkit-filter: blur(4px);
}
}
}