---
layout: default
title: Magnific Popup Documentation
description: The complete guide on how to use Magnific Popup - the open source responsive lightbox plugin.
addjs: true
canonical_url: http://dimsemenov.com/plugins/magnific-popup/documentation.html
buildtool: true
---
Here you can find the guide on how to use Magnific Popup. Besides this docs page, you can play with examples on CodePen. If you've found any mistake in this site or you know how to improve some part of this documentation - please commit on GitHub.
Please ask general questions through Stack Overflow tagged with `magnific-popup`.
If you're looking for touch-friendly popup just for images, PhotoSwipe might be a better choice.
# magnific popup docs
* This will become a table of contents (this text will be scraped).
{:toc}
## Including files
You can get Magnific Popup JS and CSS file from the build tool, from the `dist/` folder in the GitHub repository, or by compiling it yourself with Grunt.
{% highlight html %}
{% endhighlight %}
It's not required, but we recommend placing CSS files in `` and JavaScript files and initialization code in the footer of your site (before the closing `` tag). If you already have `jquery.js` on your site, don't include it a second time, or use `jQuery.noConflict();` mode. Optionally, you can include [Zepto.js](http://zeptojs.com/) instead of [jQuery](http://jquery.com), or [choose which one to include](http://stackoverflow.com/questions/8725905/zepto-fallback-to-jquery) based on browser support.
## Initializing popup
Popup initialization code should be executed after document ready, for example:
{% highlight javascript %}
$(document).ready(function() {
$('.image-link').magnificPopup({type:'image'});
});
{% endhighlight %}
There are three ways to initialize a popup:
### 1. From an HTML element
{% highlight html %}
Open popup
{% endhighlight %}
{% highlight javascript %}
$('.test-popup-link').magnificPopup({
type: 'image'
// other options
});
{% endhighlight %}
### 2. From a group of elements with one parent
Same as first one, but use this method if you are creating a popup from a list of elements in one container. Note that this method does not enable gallery mode, it just reduces the number of click event handlers; each item will be opened as a single popup. If you wish to enable gallery, add the `gallery:{enabled:true}` option.
{% highlight html %}
{% endhighlight %}
{% highlight javascript %}
$('.parent-container').magnificPopup({
delegate: 'a', // child items selector, by clicking on it popup will open
type: 'image'
// other options
});
{% endhighlight %}
### 3. From the 'items' option
The `items` option defines data for the popup item(s) and makes Magnific Popup ignore all attributes on the target DOM element. The value for `items` can be a single object or an array of objects.
{% highlight javascript %}
// Example with single object
$('#some-button').magnificPopup({
items: {
src: 'path-to-image-1.jpg'
},
type: 'image' // this is default type
});
// Example with multiple objects
$('#some-button').magnificPopup({
items: [
{
src: 'path-to-image-1.jpg'
},
{
src: 'http://vimeo.com/123123',
type: 'iframe' // this overrides default type
},
{
src: $('
Dynamically created element
'), // Dynamically created element
type: 'inline'
},
{
src: '
HTML string
',
type: 'inline'
},
{
src: '#my-popup', // CSS selector of an element on page that should be used as a popup
type: 'inline'
}
],
gallery: {
enabled: true
},
type: 'image' // this is default type
});
{% endhighlight %}
Play with [this example on CodePen](http://codepen.io/dimsemenov/pen/vKrqs).
## Content Types
By default, Magnific Popup has four types of content: `image`, `iframe`, `inline`, and `ajax`. There is no any "auto-detection" of type based on URL, so you should define it manually.
The type of a popup can be defined in a two ways:
1. Using the `type` option. E.g.: `$('.image-link').magnificPopup({type:'image'})`.
2. Using the `mfp-TYPE` CSS class (where `TYPE` is the desired content type). For example: `Open image`, `$('.image-link').magnificPopup()`.
The second option always overrides the first, so you may initialize popups with multiple content types from one call.
`inline` is the default content type (from v0.8.4), so you may skip its definition.
**The source of the the popup content** (for example, a path to an image, a path to an HTML file, a path to a video page) can be defined in a few ways:
Method #1: From the `href` attribute:
{% highlight html %}Open image{% endhighlight %}
Method #2: From the `data-mfp-src` attribute (overrides the first method):
{% highlight html %}Open image{% endhighlight %}
Method #3: From the items option
{% highlight javascript %}
$.magnificPopup.open({
items: {
src: 'some-image.jpg'
},
type: 'image'
});
{% endhighlight %}
If you want to modify how the source is parsed, you may hook into the `elementParse` callback. For example:
{% highlight javascript %}
$('.image-link').magnificPopup({
type:'image',
callbacks: {
elementParse: function(item) {
// Function will fire for each target element
// "item.el" is a target DOM element (if present)
// "item.src" is a source that you may modify
console.log(item); // Do whatever you want with "item" object
}
}
});
{% endhighlight %}
## Image Type
The path to the image must be set as the main source if you selected this type. If your popup doesn't have an image source and doesn't have an image that shouldn't be preloaded (and retina-ized, etc.), use the `inline` type.
{% highlight javascript %}
image: {
markup: '
'+
''+
''+
'
'+
''+
''+
'
'+
'
', // Popup HTML markup. `.mfp-img` div will be replaced with img tag, `.mfp-close` by close button
cursor: 'mfp-zoom-out-cur', // Class that adds zoom cursor, will be added to body. Set to null to disable zoom out cursor.
titleSrc: 'title', // Attribute of the target element that contains caption for the slide.
// Or the function that should return the title. For example:
// titleSrc: function(item) {
// return item.el.attr('title') + 'by Marsel Van Oosten';
// }
verticalFit: true, // Fits image in area vertically
tError: 'The image could not be loaded.' // Error message
}
{% endhighlight %}
Please note that Magnific Popup doesn't implement any JavaScript-based client-side caching for images. So make sure that your server [adds expires headers](https://developers.google.com/speed/docs/best-practices/caching#LeverageBrowserCaching) so the image won't be downloaded each time.
## Iframe Type
By default Magnific Popup supports only one type of URL for each service:
{% highlight javascript %}
// YouTube
"http://www.youtube.com/watch?v=7HKoqNJtMTQ"
// Vimeo
"http://vimeo.com/123123"
// Google Maps
"https://maps.google.com/maps?q=221B+Baker+Street,+London,+United+Kingdom&hl=en&t=v&hnear=221B+Baker+St,+London+NW1+6XE,+United+Kingdom"
{% endhighlight %}
But you can extend it and make it support absolutely any URL or any other service (view [example that adds Dailymotion support](http://codepen.io/dimsemenov/pen/jnohA)). Iframe options:
{% highlight javascript %}
iframe: {
markup: '
'+
''+
''+
'
', // HTML markup of popup, `mfp-close` will be replaced by the close button
patterns: {
youtube: {
index: 'youtube.com/', // String that detects type of video (in this case YouTube). Simply via url.indexOf(index).
id: 'v=', // String that splits URL in a two parts, second part should be %id%
// Or null - full URL will be returned
// Or a function that should return %id%, for example:
// id: function(url) { return 'parsed id'; }
src: '//www.youtube.com/embed/%id%?autoplay=1' // URL that will be set as a source for iframe.
},
vimeo: {
index: 'vimeo.com/',
id: '/',
src: '//player.vimeo.com/video/%id%?autoplay=1'
},
gmaps: {
index: '//maps.google.',
src: '%id%&output=embed'
}
// you may add here more sources
},
srcAction: 'iframe_src', // Templating object key. First part defines CSS selector, second attribute. "iframe_src" means: find "iframe" and set attribute "src".
}
{% endhighlight %}
## Inline Type
To create popup from inline element you need to:
1) Create a HTML element that you wish to display in popup and add it somewhere. Class `mfp-hide` is required to hide the popup from the page.
{% highlight html %}
Popup content
{% endhighlight %}
2) Style this element. Magnific Popup by default doesn't apply any styles to it, except vertical centering (if `alignTop:false`). Close button will be automatically appended inside (if `closeBtnInside:true`).
{% highlight css %}
.white-popup {
position: relative;
background: #FFF;
padding: 20px;
width: auto;
max-width: 500px;
margin: 20px auto;
}
{% endhighlight %}
3) Add button that will open the popup (source must match CSS id of an element (`#test-popup` in our case).
{% highlight html %}
Show inline popupShow inline popup
{% endhighlight %}
4) Initialize script.
{% highlight javascript %}
$('.open-popup-link').magnificPopup({
type:'inline',
midClick: true // Allow opening popup on middle mouse click. Always set it to true if you don't provide alternative source in href.
});
{% endhighlight %}
Here are some other ways to initialize popup:
{% highlight javascript %}
// From HTML string
$('button').magnificPopup({
items: {
src: '
Dynamically created popup
',
type: 'inline'
}
});
// From an element with ID #popup
$('button').magnificPopup({
items: {
src: '#popup',
type: 'inline'
}
});
// From jQuery object
$('button').magnificPopup({
items: {
src: $('
Dynamically created popup
'),
type: 'inline'
}
});
// Open directly via API
$.magnificPopup.open({
items: {
src: '
Dynamically created popup
', // can be a HTML string, jQuery object, or CSS selector
type: 'inline'
}
});
{% endhighlight %}
I have created two examples on CodePen that will help you better understand how it works:
- [Simple inline popup](http://codepen.io/dimsemenov/pen/GEKgb)
- [Advanced popup with markup and gallery mode](http://codepen.io/dimsemenov/pen/sHoxp)
## Ajax Type
To create such type of popup, first of define the path to the file that you wish to display and select `ajax` type of the popup. Popup itself should be styled in exactly the same way as an [inline popup type](#inline-type).
**Important note!** The contents of the file that you load is already a popup itself, so there must be **only one root element**.
{% highlight html %}
Show inline popup
{% endhighlight %}
{% highlight javascript %}
$('.ajax-popup-link').magnificPopup({
type: 'ajax'
});
{% endhighlight %}
Note that path to the file that will be loaded should have the same origin (e.g. be on the same domain), [learn more](http://stackoverflow.com/questions/3076414/ways-to-circumvent-the-same-origin-policy).
Ajax options:
{% highlight javascript %}
ajax: {
settings: null, // Ajax settings object that will extend default one - http://api.jquery.com/jQuery.ajax/#jQuery-ajax-settings
// For example:
// settings: {cache:false, async:false}
cursor: 'mfp-ajax-cur', // CSS class that will be added to body during the loading (adds "progress" cursor)
tError: 'The content could not be loaded.' // Error message, can contain %curr% and %total% tags if gallery is enabled
}
{% endhighlight %}
To modify content after it's loaded, or to select and show just specific element from loaded file, there is a `parseAjax` callback:
{% highlight javascript %}
callbacks: {
parseAjax: function(mfpResponse) {
// mfpResponse.data is a "data" object from ajax "success" callback
// for simple HTML file, it will be just String
// You may modify it to change contents of the popup
// For example, to show just #some-element:
// mfpResponse.data = $(mfpResponse.data).find('#some-element');
// mfpResponse.data must be a String or a DOM (jQuery) element
console.log('Ajax content loaded:', mfpResponse);
},
ajaxContentAdded: function() {
// Ajax content is loaded and appended to DOM
console.log(this.content);
}
}
{% endhighlight %}
## Options
Options should be passed to the initialization code and separated by comma, e.g.:
{% highlight javascript %}
$('.some-link').magnificPopup({
// main options
disableOn: 400,
key: 'some-key',
gallery: {
// options for gallery
enabled: true
},
image: {
// options for image content type
titleSrc: 'title'
}
});
{% endhighlight %}
Options for specific modules are explained in their sections of documentation (e.g. related to text are in translating section, related to gallery are in gallery section. Here you can find the list of general options:
### disableOn
null
If window width is less than the number in this option lightbox will not be opened and the default behavior of the element will be triggered. Set to `0` to disable behavior. Option works only when you initialize Magnific Popup from DOM element.
Can also accept Function as a parameter, which should return `true` if lightbox can be opened and `false` otherwise. For example:
{% highlight javascript %}
disableOn: function() {
if( $(window).width() < 600 ) {
return false;
}
return true;
}
{% endhighlight %}
### key
null
"Key" option is a unique identifier of a single or a group of popups with the same structure. If you will not define it, DOM elements will be created and destroyed each time when you open and close popup.
You may (and should) set an equal key to different popups if their markup matches. By markup I mean options that change HTML structure of the popup (e.g. close icon placement and HTML code of it).
For example: you have many popups that show title, some text and button - you may use one key for all of them, so only one instance of this element is created. Same for popup that always contains image and caption.
You can delete cached templates like so:
// delete template with key "your-key"
delete $.magnificPopup.instance.popupsCache['your-key'];
// delete all templates
$.magnificPopup.instance.popupsCache = {};
### midClick
false
If set to `true` lightbox is opened if the user clicked on the middle mouse button, or click with Command/Ctrl key. Option works only when you initialize Magnific Popup from DOM element.
### mainClass
empty string
String that contains classes that will be added to the root element of popup wrapper and to dark overlay. For example `"myClass"`, can also contain multiple classes - `'myClassOne myClassTwo'`.
### preloader
true
Preloader in Magnific Popup is used as an indicator of current status. If option enabled, it's always present in DOM only text inside of it changes. Below you can see explanation of CSS names that are applied to container that holds preloader and content area depending on the state of current item:
{% highlight css %}
/* Content loading is in progress */
.mfp-s-loading { }
/* Content successfully loaded */
.mfp-s-ready { }
/* Error during loading */
.mfp-s-error { }
{% endhighlight %}
For example, if you want your error message to be in red add such CSS:
{% highlight css %}
.mfp-s-error .mfp-preloader {
color: red;
}
{% endhighlight %}
You can trigger change of status manually by calling `instance.updateStatus('error', 'error message')`.
### focus
empty string
String with CSS selector of an element inside popup that should be focused. Ideally it should be the first element of popup that can be focused. For example `'input'` or `'#login-input'`. Leave empty to focus the popup itself.
### closeOnContentClick
false
Close popup when user clicks on content of it. It's recommended to enable this option when you have only image in popup.
### closeOnBgClick
true
Close the popup when user clicks on the dark overlay.
### closeBtnInside
true
If enabled, Magnific Popup will put close button inside content of popup, and wrapper will get class `mfp-close-btn-in` (which in default CSS file makes color of it change). If markup of popup item is defined element with class `mfp-close` it will be replaced with this button, otherwise close button will be appended directly.
### showCloseBtn
true
Controls whether the close button will be displayed or not.
### enableEscapeKey
true
Controls whether pressing the escape key will dismiss the active popup or
not.
### modal
false
When set to `true`, the popup will have a modal-like behavior: it won't be
possible to dismiss it by usual means (close button, escape key, or
clicking in the overlay).
This is a shortcut to set ``closeOnContentClick``, ``closeOnBgClick``,
``showCloseBtn``, and ``enableEscapeKey`` to ``false``.
### alignTop
false
If set to `true` popup is aligned to top instead of to center. (basically all this option does is adds `mfp-align-top` CSS class to popup which removes styles that align popup to center).
### index
null
Used for gallery. Defines starting index. If popup is initialised from DOM element, this option will be ignored.
### fixedContentPos
auto
Popup content position. Can be `"auto"`, `true` or `false`. If set to `true` - fixed position will be used, to `false` - absolute position based on current scroll. If set to `"auto"` popup will automatically disable this option when browser doesn't support fixed position properly.
### fixedBgPos
auto
Same as an option above, but it defines position property of the dark transluscent overlay. If set to `false` - huge tall overlay will be generated that equals height of window to emulate fixed position. It's recommended to set this option to `true` if you animate this dark overlay and content is most likely will not be zoomed, as size of it will be much smaller.
### overflowY
auto
Defines scrollbar of the popup, works as overflow-y CSS property - any CSS acceptable value is allowed (e.g. `auto`, `scroll`, `hidden`). Option is applied only when fixed position is enabled.
There is no option `overflowX`, but you may easily emulate it just via CSS.
### removalDelay
0
Delay before popup is removed from DOM. Used for the [animation](#animation).
### closeMarkup
<button title="%title%" type="button" class="mfp-close">×</button>
Markup of close button. %title% will be replaced with option `tClose`.
### prependTo
document.body
The DOM element to which popup will be added. Useful when you're using ASP.NET where popup should be inside `form`. Option available since 2013/12/04.
### autoFocusLast
true
If set to `true` last focused element before popup showup will be focused after popup close. Option available since 2015/12/16.
## Gallery
The gallery module allows you to switch the content of the popup and adds navigation arrows. It can switch and mix any types of content, not just images. Gallery options:
{% highlight javascript %}
gallery: {
enabled: false, // set to true to enable gallery
preload: [0,2], // read about this option in next Lazy-loading section
navigateByImgClick: true,
arrowMarkup: '', // markup of an arrow button
tPrev: 'Previous (Left arrow key)', // title for left button
tNext: 'Next (Right arrow key)', // title for right button
tCounter: '%curr% of %total%' // markup of counter
}
{% endhighlight %}
Example:
{% highlight javascript %}
// This will create a single gallery from all elements that have class "gallery-item"
$('.gallery-item').magnificPopup({
type: 'image',
gallery:{
enabled:true
}
});
{% endhighlight %}
### Multiple galleries
To have multiple galleries on a page, you need to create a new instance of Magnific Popup for each separate gallery. For example
{% highlight html %}
Improve this documentation page (simply submit commit via GitHub). Any improvements, including your own CodePen examples are very welcome. And, lastly, don't forget to star the script on GitHub: