- Setup
- How to Use
- Media types
  - Images
  - Inline
  - Ajax
  - Iframe
- Embedding
- Options
- Api
- Modules
- FAQ

## Setup

You can install fancyBox by linking `.css` and `.js` to your html file. Make sure you also load the jQuery library. Below is a basic HTML template to use as an example:

    <!DOCTYPE html>
    <html>
    <head>
    	<meta charset="utf-8">
    	<title>My page</title>

    	<!-- CSS -->
    	<link rel="stylesheet" type="text/css" href="jquery.fancybox.min.css">
    </head>
    <body>

    	<!-- Your HTML content goes here -->

    	<!-- JS -->
    	<script src="//code.jquery.com/jquery-3.1.1.min.js"></script>
    	<script src="jquery.fancybox.min.js"></script>
    </body>
    </html>

Tips:

- Make sure you add the jQuery library first
- If you already have jQuery on your page, you shouldn't include it second time
- Do not include both fancybox.js and fancybox.min.js files

### Downloading using Bower

You can install the latest version of fancyBox with the command:

    bower install fancybox

This will install fancyBox to Bower's install directory, the default being `bower_components`.
Within `bower_components/fancybox/dist/` you will find an uncompressed release and a compressed release.

### Using jQuery with a CDN

CDNJS CDN also host compressed and uncompressed versions of fancyBox -
https://cdnjs.com/libraries/fancybox/

## How to Use

There are a few ways you can use fancyBox.

### Initialize with data attributes

The most basic way to use fancyBox is by adding the `data-fancybox` attribute to a link. A caption can be added using the `data-caption` attribute. Example:

    <a href="image.jpg" data-fancybox data-caption="My caption">
    	<img src="thumbnail.jpg" alt="" />
    </a>

If you have a group of items, you can use the same attribute `data-fancybox` value for each of them to create a gallery. Each group should have a unique value:

    <a href="image_1.jpg" data-fancybox="group" data-caption="Caption #1">
    	<img src="thumbnail_1.jpg" alt="" />
    </a>

    <a href="image_2.jpg" data-fancybox="group" data-caption="Caption #2">
    	<img src="thumbnail_2.jpg" alt="" />
    </a>

Tip: fancyBox attempts to automatically detect the type of content based on the given url. If it cannot be detected, the type can also be set manually using `data-type` attribute:

    <a href="images.php?id=123" data-type="image" data-caption="Caption">
    	Show image
    </a>

### Initialize with JavaScript

To bind fancyBox events on any element, select with a jQuery selector and call the `fancybox` method:

    <script type="text/javascript">
    	$("[data-fancybox]").fancybox({
    		// Options will go here
    	});
    </script>

### Manual calling of fancyBox

fancyBox can be activated at any point within Javascript and therefore does not necessarily need a trigger element. Example of displaying a simple message:

    $.fancybox.open('<div class="message"><h2>Hello!</h2><p>You are awesome!</p></div>');

See API section for more information.

## Media types

### Images

The standard way of using fancyBox is with a number of thumbnail images that link to larger images:

    <a href="image.jpg" data-fancybox="images" data-caption="My caption">
    	<img src="thumbnail.jpg" alt="" />
    </a>

View demo on CodePen

By default, fancyBox fully preloads an image before displaying it. You can choose to display the image right away. It will render and show the full size image while the data is being received. To do so, some attributes are necessary:

- `data-width` - the real width of the image
- `data-height` - the real height of the image

    <a href="image.jpg" data-fancybox="images" data-width="2048" data-height="1365">
        <img src="thumbnail.jpg" />
    </a>

View demo on CodePen

fancyBox supports "scrset" so I can display different images based on viewport width. You can use this to improve download times for mobile users and over time save bandwidth. Example:

    <a href="medium.jpg" data-fancybox="images" data-srcset="large.jpg 1600w, medium.jpg 1200w, small.jpg 640w">
    	<img src="thumbnail.jpg" />
    </a>

View demo on CodePen

It is also possible to protect images from downloading by right-click. While this does not protect from truly determined users, it should discourage the vast majority from ripping off your files.

    $('[data-fancybox]').fancybox({
    	image : {
    		protect: true
    	}
    });

View demo on CodePen

### Inline

For your Inline HTML you have to place a DIV Container into the content of the page:

    <div style="display: none;" id="hidden-content">
    	<h2>Hello</h2>
    	<p>You are awesome.</p>
    </div>

And then simply create a link using `data-src` attribute that matches CSS id selector of the element you want to open (`#hidden-content` in this example):

    <a data-fancybox data-src="#hidden-content" href="javascript:;">
    	Hidden div
    </a>

View demo on CodePen

### Ajax

To load content via AJAX, you need to add a `data-type="ajax"` attribute to your link:

    <a data-fancybox data-type="ajax" data-src="my_page.com/path/to/ajax/" href="javascript:;">
    	AJAX content
    </a>

View demo on CodePen

Additionally it is possible to define a selector with the `data-selector` attribute to show only a part of the response. The selector can be any string, that is a valid jQuery selector:

    <a data-fancybox data-type="ajax" data-src="my_page.com/path/to/ajax/" data-selector="#two" href="javascript:;">
    	AJAX content
    </a>

View demo on CodePen

### Iframe

If the content can be shown on a page, and placement in an iframe is not blocked by script or security configuration of that page, it can be presented in a fancyBox:

    <a data-fancybox data-src="http://codepen.io/fancyapps/full/jyEGGG/" href="javascript:;">
    	Webpage
    </a>

    <a data-fancybox data-src="http://www.adobe.com/content/dam/Adobe/en/devnet/acrobat/pdfs/pdf_open_parameters.pdf" href="javascript:;">
    	Sample PDF
    </a>

View demo on CodePen

To access and control fancyBox in parent window from inside an iframe:

    // Adjust iframe height according to the contents
    parent.jQuery.fancybox.getInstance().update();

    // Close current fancyBox instance
    parent.jQuery.fancybox.getInstance().close();

Iframe dimensions can be controlled by CSS:

    .fancybox-slide--iframe .fancybox-content {
    	width  : 800px;
    	height : 600px;
    	max-width  : 80%;
    	max-height : 80%;
    	margin: 0;
    }

These CSS rules can be overridden by JS, if needed:

    $("[data-fancybox]").fancybox({
    	iframe : {
    		css : {
    			width : '600px'
    		}
    	}
    });

If you have not disabled iframe preloading (using an "preload" option), then the script will atempt to calculate content dimensions and will adjust width/height of iframe to fit with content in it. Keep in mind, that due to same origin policy, there are some limitations.

## Embedding

Supported sites can be used with fancyBox by just providing the page URL:

    <a data-fancybox href="https://www.youtube.com/watch?v=_sI_Ps7JSEk">
      YouTube video
    </a>

    <a data-fancybox href="https://vimeo.com/191947042">
      Vimeo video
    </a>

    <a data-fancybox href="https://www.google.com/maps/place/Googleplex/@37.4220041,-122.0833494,17z/data=!4m5!3m4!1s0x0:0x6c296c66619367e0!8m2!3d37.4219998!4d-122.0840572">
    	Google Map
    </a>

    <a data-fancybox href="https://www.instagram.com/p/BNXYW8-goPI/?taken-by=jamesrelfdyer" data-caption="<span title=&quot;Edited&quot;>balloon rides at dawn ✨🎈<br>was such a magical experience floating over napa valley as the golden light hit the hills.<br><a href=&quot;https://www.instagram.com/jamesrelfdyer/&quot;>@jamesrelfdyer</a></span>">
    	Instagram photo
    </a>

View demo on CodePen

### Video dimensions

Resize video display with the following CSS:

    .fancybox-slide--video .fancybox-content {
    	width  : 800px;
    	height : 600px;
    	max-width  : 80%;
    	max-height : 80%;
    }

View demo on CodePen

Obviously, you can choose any size you like, any combination with `min`/`max` values.
Aspect ratio lock for videos is not implemented yet, but if you wish, you can use this snippet.

### Video parameters

Controlling a video via URL parameters:

    <a data-fancybox href="https://www.youtube.com/watch?v=_sI_Ps7JSEk&amp;autoplay=1&amp;rel=0&amp;controls=0&amp;showinfo=0">
      YouTube video - hide controls and info
    </a>

    <a data-fancybox href="https://vimeo.com/191947042?color=f00">
      Vimeo video - custom color
    </a>

View demo on CodePen

Via JavaScript:

    $('[data-fancybox]').fancybox({
    	youtube : {
    		controls : 0,
    		showinfo : 0
    	},
    	vimeo : {
    		color : 'f00'
    	}
    });

View demo on CodePen

## Options

Available options listed below.

    defaults = {

    	// Animation duration in ms
    	speed : 330,

    	// Enable infinite gallery navigation
    	loop : true,

    	// Should zoom animation change opacity, too
    	// If opacity is 'auto', then fade-out if image and thumbnail have different aspect ratios
    	opacity : 'auto',

    	// Space around image, ignored if zoomed-in or viewport smaller than 800px
    	margin : [44, 0],

    	// Horizontal space between slides
    	gutter : 30,

    	// Should display toolbars
    	infobar : true,
    	buttons : true,

    	// What buttons should appear in the toolbar
    	slideShow  : true,
    	fullScreen : true,
    	thumbs     : true,
    	closeBtn   : true,

    	// Should apply small close button at top right corner of the content
    	// If 'auto' - will be set for content having type 'html', 'inline' or 'ajax'
    	smallBtn : 'auto',

    	image : {

    		// Wait for images to load before displaying
    		// Requires predefined image dimensions
    		// If 'auto' - will zoom in thumbnail if 'width' and 'height' attributes are found
    		preload : "auto",

    		// Protect an image from downloading by right-click
    		protect : false

    	},

    	ajax : {

    		// Object containing settings for ajax request
    		settings : {

    			// This helps to indicate that request comes from the modal
    			// Feel free to change naming
    			data : {
    				fancybox : true
    			}
    		}

    	},

    	iframe : {

    		// Iframe template
    		tpl : '<iframe id="fancybox-frame{rnd}" name="fancybox-frame{rnd}" class="fancybox-iframe" frameborder="0" vspace="0" hspace="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen allowtransparency="true" src=""></iframe>',

    		// Preload iframe before displaying it
    		// This allows to calculate iframe content width and height
    		// (note: Due to "Same Origin Policy", you can't get cross domain data).
    		preload : true,

    		// Scrolling attribute for iframe tag
    		scrolling : 'no',

    		// Custom CSS styling for iframe wrapping element
    		css : {}

    	},

    	// Custom CSS class for layout
    	baseClass : '',

    	// Custom CSS class for slide element
    	slideClass : '',

    	// Base template for layout
    	baseTpl	: '<div class="fancybox-container" role="dialog" tabindex="-1">' +
    			'<div class="fancybox-bg"></div>' +
    			'<div class="fancybox-controls">' +
    				'<div class="fancybox-infobar">' +
    					'<button data-fancybox-previous class="fancybox-button fancybox-button--left" title="Previous"></button>' +
    					'<div class="fancybox-infobar__body">' +
    						'<span class="js-fancybox-index"></span>&nbsp;/&nbsp;<span class="js-fancybox-count"></span>' +
    					'</div>' +
    					'<button data-fancybox-next class="fancybox-button fancybox-button--right" title="Next"></button>' +
    				'</div>' +
    				'<div class="fancybox-buttons">' +
    					'<button data-fancybox-close class="fancybox-button fancybox-button--close" title="Close (Esc)"></button>' +
    				'</div>' +
    			'</div>' +
    			'<div class="fancybox-slider-wrap">' +
    				'<div class="fancybox-slider"></div>' +
    			'</div>' +
    			'<div class="fancybox-caption-wrap"><div class="fancybox-caption"></div></div>' +
    		'</div>',

    	// Loading indicator template
    	spinnerTpl : '<div class="fancybox-loading"></div>',

    	// Error message template
    	errorTpl : '<div class="fancybox-error"><p>The requested content cannot be loaded. <br /> Please try again later.<p></div>',

    	// This will be appended to html content, if "smallBtn" option is not set to false
    	closeTpl : '<button data-fancybox-close class="fancybox-close-small"></button>',

    	// Container is injected into this element
    	parentEl : 'body',

    	// Enable gestures (tap, zoom, pan and pinch)
    	touch : true,

    	// Enable keyboard navigation
    	keyboard : true,

    	// Try to focus on first focusable element after opening
    	focus : true,

    	// Close when clicked outside of the content
    	closeClickOutside : true,

    	// Callbacks; See Documentation/API/Events for description and samples
    	beforeLoad	 : $.noop,
    	afterLoad    : $.noop,
    	beforeMove 	 : $.noop,
    	afterMove    : $.noop,
    	onComplete	 : $.noop,

    	onInit       : $.noop,
    	beforeClose	 : $.noop,
    	afterClose	 : $.noop,
    	onActivate   : $.noop,
    	onDeactivate : $.noop
    }

Set instance options by passing a valid object to `fancybox()` method:

    $("[data-fancybox]").fancybox({
    	image : {
    		protect : true
    	}
    });

Plugin options / defaults are exposed in `$.fancybox.defaults` namespace so you can easily adjust them globally:

    $.fancybox.defaults.speed = 600;

Custom options for each element individually can be set by adding a `data-options` attribute to the element. This attribute should contain the properly formatted JSON object:

    <a data-fancybox data-options='{"caption" : "My caption", "src : "iframe.html"}' href="javascript:;">
    	Open external page using iframe
    </a>

## API

The fancyBox API offers a couple of methods to control fancyBox. This gives you the ability to extend the plugin and to integrate it with other web application components.

### Core methods

Core methods are methods which affect/handle instances:

    // Close only the currently active or all fancyBox instances
    $.fancybox.close( all );

    // Open the fancyBox right away
    $.fancybox.open( items, opts, index );

When calling fancyBox manually, each group item should follow this pattern:

    {
    	src  : '' // Source of the content
    	type : '' // Content type: image|inline|ajax|iframe|html (optional)
    	opts : {} // Object containing item options (optional)
    }

Example of opening image gallery:

    $.fancybox.open([
    	{
    		src  : '1_b.jpg',
    		opts : {
    			caption : 'First caption'
    		}
    	},
    	{
    		src  : '2_b.jpg',
    		opts : {
    			caption : 'Second caption'
    		}
    	}
    ], {
    	loop : false
    });

View demo on CodePen

It is also possible to pass only one object. Example of opening inline content:

    $.fancybox.open({
    	src  : '#hidden-content',
    	type : 'inline',
    	opts : {
    		onComplete : function() {
    			console.info('done!');
    		}
    	}
    });

View demo on CodePen

If you wish to display some html content (for example, a message), then you can use a simpler syntax. It is advised to use a wrapper around your content.

    $.fancybox.open('<div class="message"><h2>Hello!</h2><p>You are awesome!</p></div>');

View demo on CodePen

### Instance methods

In order to use these methods, you need an instance of the plugin's object:

    var $instance = $.fancybox.getInstance();

Or you can can just use fancyBox constructor:

    var $instance = $("[data-fancybox]").fancybox();

Once you have a reference to fancyBox instance the following methods are available:

    // Go to next gallery item
    $instance.next( duration );

    // Go to previous gallery item
    $instance.previous( duration );

    // Switch to the other gallery item; accepts integer argument (an index of the desired item)
    $instance.jumpTo( index, duration );

    // Check if current image dimensions are smaller than actual
    $instance.isScaledDown();

    // Scale image to the actual size of the image
    $instance.scaleToActual( x, y, duration );

    // Check if image dimensions exceed parent element
    $instance.canPan();

    // Scale image to fit inside parent element
    $instance.scaleToFit( duration );

    // Move slider to current position
    // Update all slides (and their content) if needed
    $instance.update( andSlides, andContent, duration );

    // Update slide position and make content fit in slide if needed
    $instance.updateSlide( slide, andContent );

    // Update infobar values, navigation button states and reveal caption
    $instance.updateControls( force );

    // Load custom content into the slide
    $instance.setContent( slide, content );

    // Try to find and focus on the first focusable element
    $instance.focus();

    // Activates current instance, brings it to the front
    $instance.activate();

    // Close instance
    $instance.close();

You can also do something like this:

    $.fancybox.getInstance().jumpTo(1);

or simply:

    $.fancybox.getInstance('jumpTo', 1);

### Events

fancyBox fires several events.

    beforeLoad	 : Before the content of a slide is being loaded
    afterLoad    : When the content of a slide is done loading
    beforeMove 	 : Before slide change transition starts
    afterMove    : After slide change transition is complete
    onComplete	 : When slide change is complete and content has been loaded

    onInit	 	 : When instance has been initialized
    beforeClose	 : Before instance is closed
    afterClose	 : After instance has been closed
    onActivate   : When instance is brought to front
    onDeactivate : When other instance has been activated

Event callbacks can be set as function properties of the options object passed to fancyBox initialization function:

    <script type="text/javascript">
    	$("[data-fancybox]").fancybox({
    		onComplete: function( instance, slide ) {

    			// Tip: Each event passes useful information within the event object:

    			// Object containing references to interface elements
    			// (background, buttons, caption, etc)
    			// console.info( instance.$refs );

    			// Current slide options
    			// console.info( slide.opts );

    			// Clicked element
    			// console.info( slide.opts.$orig );

    			// Reference to DOM element of the slide
    			// console.info( slide.$slide );

    		}
    	});
    </script>

Each callback receives two parameters - current fancyBox instance and current gallery object, if exists.

It is also possible to attach event handler for all instances. To prevent interfering with other scripts, these events have been namespaced to `.fb`. These handlers receive 3 parameters - event, current fancyBox instance and current gallery object.

Here is an example of binding to the `onComplete` event:

    $(document).on('onComplete.fb', function( e, instance, slide ) {
    	// Your code goes here
    });

If you wish to prevent closing of the modal, for example, if form is not validating, you can use `beforeClose` callback. Simply return `false`:

    beforeClose : function( instance, current, e ) {
    	if ( $('#my-field').val() == '' ) {
    		return false;
    	}
    }

## Modules

fancyBox code is split into several files (modules) that extend core functionality. You can build your own fancyBox version by excluding unnecessary modules, if needed. Each one has their own `js` and/or `css` files.

Some modules can be customized and controlled programmatically. List of all possible options:

    slideShow : {
    	speed : 3000 // Slideshow speed in ms
    },
    touch : {
    	vertical : true // Allow vertical swipe
    },
    thumbs : {
    	showOnStart   : false, // Display thumbnails on opening
    	hideOnClosing : true   // Hide thumbnail grid when closing animation starts
    },
    fullScreen : {
    	requestOnStart : false // Request fullscreen mode on opening
    },
    hash : false // Hash value

Example (show thumbnails on start):

    $('[data-fancybox="images"]').fancybox({
    	thumbs : {
    		showOnStart : true
    	}
    })

View demo on CodePen

If you would inspect fancyBox instance object, you would find keys that names ar captialized - these are references for each module object. Also, you would notice that fancyBox uses common naming convention to prefix jQuery objects with `$`.

This is how you, for example, can access thumbnail grid element:

    $.fancybox.getInstance().Thumbs.$grid

This example shows how to call method that toggles thumbnails:

    $.fancybox.getInstance().Thumbs.toggle();

List of available methods:

    Thumbs.focus()
    Thumbs.close();
    Thumbs.update();
    Thumbs.hide();
    Thumbs.show();
    Thumbs.toggle();

    FullScreen.request( elem );
    FullScreen.exit();
    FullScreen.toggle( elem );
    FullScreen.isFullscreen();
    FullScreen.enabled();

    SlideShow.start();
    SlideShow.stop();
    SlideShow.toggle();

If you wish to disable hash module, use this snippet (after including JS file):

    $.fancybox.defaults.hash = false;

## FAQ

### Opening/closing causes fixed element to jump

Simply add `compensate-for-scrollbar` CSS class to your fixed positioned elements. Example of using Bootstrap navbar component:

    <nav class="navbar navbar-inverse navbar-fixed-top compensate-for-scrollbar">
    	<div class="container">
    		..
    	</div>
    </nav>

The script measures width of the scrollbar and creates `compensate-for-scrollbar` CSS class that uses this value for `margin-right` property. Therefore, if your element has `width:100%`, you should positon it using `left` and `right` properties instead. Example:

    .navbar {
    	position: fixed;
    	top: 0;
    	left: 0;
    	right: 0;
    }

### How to customize caption

You can use `caption` option that accepts a function and is called for each group element. Example of appending image download link:

    $( '[data-fancybox]' ).fancybox({
    	caption : function( instance, item ) {
    		var caption, link;

    		if ( item.type === 'image' ) {
    			caption = $(this).data('caption');
    			link    = '<a href="' + item.src + '">Download image</a>';

    			return (caption ? caption + '<br />' : '') + link;
    		}
    	}
    });

View demo on CodePen

Inside `caption` method, `this` refers to the clicked element. Example of using different source for caption:

    $( '[data-fancybox]' ).fancybox({
    	caption : function( instance, item ) {
    		return $(this).find('figcaption').html();
    	}
    });

View demo on CodePen

### How to create custom button in the toolbar

Example of using callback to access toolbar element and append custom button:

    $( '[data-fancybox]' ).fancybox({
    	onInit : function( instance ) {
    		instance.$refs.downloadButton = $('<a class="fancybox-button fancybox-download"></a>')
    			.appendTo( instance.$refs.buttons );
    	},
    	beforeMove: function( instance, current ) {
    		instance.$refs.downloadButton.attr('href', current.src);
    	}
    });

View demo on CodePen

### How to reposition thumbnail grid

There is currenty no JS option to change thumbnail grid position. But fancyBox is designed so that you can use CSS to change position or dimension for each block (e.g., content area, caption or thumbnail grid). This gives you freedom to completely change the look and feel of the modal window, if needed. View demo on CodePen