- Setup
- How to Use
- Media types
  - Images
  - Inline
  - Ajax
  - Iframe
- Embedding
- Options
- Api
- 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.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

## 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 style="padding:50px;"><h3>You are awesome!</h3></div>');

It is also possible to pass a list of objects and group options:

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

The object returned is a new instance of the fancyBox and allows to access the public API methods provided by the fancyBox.

## 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

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

Tip: To 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();

## 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.

### 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>',

    	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
    	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.

### 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( immediately, andSlides, andContent );

    // 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);

### Core methods

Core methods are methods which affect/handle instances.

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

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

### 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

To prevent interfering with other scripts, all events have been namespaced to `.fb`. Here is an example of binding to the `onComplete` event.

    $(document).on('onComplete.fb', function( e, instance, slide ) {

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

    	// Object containing references to interface elements
    	// console.info( instance.$refs );

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

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

    });

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 ) { }
    	});
    </script>

## FAQ

### Opening/closing causes fixed header 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>

### How to customize caption

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

### 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