PageRenderTime 59ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/website/documentation.md

https://github.com/pitankar/Magnific-Popup
Markdown | 1197 lines | 828 code | 369 blank | 0 comment | 0 complexity | b29a9d8f0559d03ec225fe100dee232f MD5 | raw file
  1. ---
  2. layout: default
  3. title: Magnific Popup Documentation
  4. description: The complete guide on how to use Magnific Popup - the open source responsive lightbox plugin.
  5. addjs: true
  6. canonical_url: http://dimsemenov.com/plugins/magnific-popup/documentation.html
  7. buildtool: true
  8. ---
  9. <div id="documentation-intro">
  10. <h1><a href="http://dimsemenov.com/plugins/magnific-popup/">Magnific Popup</a> Documentation</h1>
  11. <p><a href="https://github.com/dimsemenov/Magnific-Popup/">Project on Github</a> &middot; <a href="#mfp-build-tool" class="mfp-build-tool-link">Build tool</a> &middot; <a href="http://twitter.com/dimsemenov">Twitter of developer</a> &middot; <a href="http://dimsemenov.com/subscribe.html">Newsletter of developer</a></p>
  12. </div>
  13. <!-- DOCUMENTATION START -->
  14. Here you can find the guide on how to use Magnific Popup. Besides this docs page, you can <a href="http://codepen.io/collection/nLcqo">play with examples on CodePen</a>. If you've found any mistake in this site or you know how to improve some part of this documentation - please <a href="https://github.com/dimsemenov/Magnific-Popup/blob/master/website/documentation.md">commit on GitHub</a>.
  15. Please ask general questions through <a href="http://stackoverflow.com/questions/ask?tags=magnific-popup">StackOverflow</a> tagged with `magnific-popup`.
  16. # magnific popup docs
  17. * This will become a table of contents (this text will be scraped).
  18. {:toc}
  19. ## Including files
  20. You can get Magnific Popup JS and CSS file from the <a href="#mfp-build-tool" class="mfp-build-tool-link">build tool</a>, from the `dist/` folder in the <a href="https://github.com/dimsemenov/Magnific-Popup">GitHub repository</a>, or by compiling it yourself with Grunt.
  21. {% highlight html %}
  22. <!-- Magnific Popup core CSS file -->
  23. <link rel="stylesheet" href="magnific-popup/magnific-popup.css">
  24. <!-- jQuery 1.7.2+ or Zepto.js 1.0+ -->
  25. <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
  26. <!-- Magnific Popup core JS file -->
  27. <script src="magnific-popup/jquery.magnific-popup.js"></script>
  28. {% endhighlight %}
  29. It's not required, but we recommend placing CSS files in `<head>` and JavaScript files and initialization code in the footer of your site (before the closing `</body>` tag).<br/> 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.
  30. ## Initializing popup
  31. Popup initialization code should be executed after document ready, for example:
  32. {% highlight javascript %}
  33. $(document).ready(function() {
  34. $('.image-link').magnificPopup({type:'image'});
  35. });
  36. {% endhighlight %}
  37. There are three ways to initialize a popup:
  38. ### 1. From an HTML element
  39. {% highlight html %}
  40. <a class="test-popup-link" href="path-to-image.jpg">Open popup</a>
  41. {% endhighlight %}
  42. {% highlight javascript %}
  43. $('.test-popup-link').magnificPopup({
  44. type: 'image'
  45. // other options
  46. });
  47. {% endhighlight %}
  48. ### 2. From a group of elements with one parent
  49. 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.
  50. {% highlight html %}
  51. <div class="parent-container">
  52. <a href="path-to-image-1.jpg">Open popup 1</a>
  53. <a href="path-to-image-2.jpg">Open popup 2</a>
  54. <a href="path-to-image-3.jpg">Open popup 3</a>
  55. </div>
  56. {% endhighlight %}
  57. {% highlight javascript %}
  58. $('.parent-container').magnificPopup({
  59. delegate: 'a', // child items selector, by clicking on it popup will open
  60. type: 'image'
  61. // other options
  62. });
  63. {% endhighlight %}
  64. ### 3. From the 'items' option
  65. 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.
  66. {% highlight javascript %}
  67. // Example with single object
  68. $('#some-button').magnificPopup({
  69. items: {
  70. src: 'path-to-image-1.jpg'
  71. },
  72. type: 'image' // this is default type
  73. });
  74. // Example with multiple objects
  75. $('#some-button').magnificPopup({
  76. items: [
  77. {
  78. src: 'path-to-image-1.jpg'
  79. },
  80. {
  81. src: 'http://vimeo.com/123123',
  82. type: 'iframe' // this overrides default type
  83. },
  84. {
  85. src: $('<div>Dynamically created element</div>'), // Dynamically created element
  86. type: 'inline'
  87. },
  88. {
  89. src: '<div>HTML string</div>',
  90. type: 'inline'
  91. },
  92. {
  93. src: '#my-popup', // CSS selector of an element on page that should be used as a popup
  94. type: 'inline'
  95. }
  96. ],
  97. gallery: {
  98. enabled: true
  99. },
  100. type: 'image' // this is default type
  101. });
  102. {% endhighlight %}
  103. Play with [this example on CodePen](http://codepen.io/dimsemenov/pen/vKrqs).
  104. ## Content Types
  105. By default, Magnific Popup has 4 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.
  106. The type of a popup can be defined in a two ways:
  107. 1. Using the `type` option. E.g.: `$('.image-link').magnificPopup({type:'image'})`.
  108. 2. Using the `mfp-TYPE` CSS class (where `TYPE` is the desired content type). For example: `<a class="mfp-image image-link">Open image</a>`, `$('.image-link').magnificPopup()`.
  109. The second option always overrides the first, so you may initialize popups with multiple content types from one call.
  110. `inline` is the default content type (from v0.8.4), so you may skip its definition.
  111. <br/>
  112. **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:
  113. Method #1: From the `href` attribute:
  114. {% highlight html %}<a href="image-for-popup.jpg">Open image</a>{% endhighlight %}
  115. Method #2: From the `data-mfp-src` attribute (overrides the first method):
  116. {% highlight html %}<a href="some-image.jpg" data-mfp-src="image-for-popup.jpg">Open image</a>{% endhighlight %}
  117. Method #3: From the <code>items</code> option
  118. {% highlight javascript %}
  119. $.magnificPopup.open({
  120. items: {
  121. src: 'some-image.jpg'
  122. },
  123. type: 'image'
  124. });
  125. {% endhighlight %}
  126. If you want to modify how the source is parsed, you may hook into the `elementParse` callback. For example:
  127. {% highlight javascript %}
  128. $('.image-link').magnificPopup({
  129. type:'image',
  130. callbacks: {
  131. elementParse: function(item) {
  132. // Function will fire for each target element
  133. // "item.el" is a target DOM element (if present)
  134. // "item.src" is a source that you may modify
  135. console.log(item); // Do whatever you want with "item" object
  136. }
  137. }
  138. });
  139. {% endhighlight %}
  140. ## Image Type
  141. 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.
  142. {% highlight javascript %}
  143. image: {
  144. markup: '<div class="mfp-figure">'+
  145. '<div class="mfp-close"></div>'+
  146. '<div class="mfp-img"></div>'+
  147. '<div class="mfp-bottom-bar">'+
  148. '<div class="mfp-title"></div>'+
  149. '<div class="mfp-counter"></div>'+
  150. '</div>'+
  151. '</div>', // Popup HTML markup. `.mfp-img` div will be replaced with img tag, `.mfp-close` by close button
  152. cursor: 'mfp-zoom-out-cur', // Class that adds zoom cursor, will be added to body. Set to null to disable zoom out cursor.
  153. titleSrc: 'title', // Attribute of the target element that contains caption for the slide.
  154. // Or the function that should return the title. For example:
  155. // titleSrc: function(item) {
  156. // return item.el.attr('title') + '<small>by Marsel Van Oosten</small>';
  157. // }
  158. verticalFit: true, // Fits image in area vertically
  159. tError: '<a href="%url%">The image</a> could not be loaded.' // Error message
  160. }
  161. {% endhighlight %}
  162. 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.
  163. ## Iframe Type
  164. By default Magnific Popup supports only one type of URL for each service:
  165. {% highlight javascript %}
  166. // YouTube
  167. "http://www.youtube.com/watch?v=7HKoqNJtMTQ"
  168. // Vimeo
  169. "http://vimeo.com/123123"
  170. // Google Maps
  171. "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"
  172. {% endhighlight %}
  173. 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:
  174. {% highlight javascript %}
  175. iframe: {
  176. markup: '<div class="mfp-iframe-scaler">'+
  177. '<div class="mfp-close"></div>'+
  178. '<iframe class="mfp-iframe" frameborder="0" allowfullscreen></iframe>'+
  179. '</div>', // HTML markup of popup, `mfp-close` will be replaced by the close button
  180. patterns: {
  181. youtube: {
  182. index: 'youtube.com/', // String that detects type of video (in this case YouTube). Simply via url.indexOf(index).
  183. id: 'v=', // String that splits URL in a two parts, second part should be %id%
  184. // Or null - full URL will be returned
  185. // Or a function that should return %id%, for example:
  186. // id: function(url) { return 'parsed id'; }
  187. src: '//www.youtube.com/embed/%id%?autoplay=1' // URL that will be set as a source for iframe.
  188. },
  189. vimeo: {
  190. index: 'vimeo.com/',
  191. id: '/',
  192. src: '//player.vimeo.com/video/%id%?autoplay=1'
  193. },
  194. gmaps: {
  195. index: '//maps.google.',
  196. src: '%id%&output=embed'
  197. }
  198. // you may add here more sources
  199. },
  200. srcAction: 'iframe_src', // Templating object key. First part defines CSS selector, second attribute. "iframe_src" means: find "iframe" and set attribute "src".
  201. }
  202. {% endhighlight %}
  203. ## Inline Type
  204. To create popup from inline element you need to:
  205. 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.
  206. {% highlight html %}
  207. <div id="test-popup" class="white-popup mfp-hide">
  208. Popup content
  209. </div>
  210. {% endhighlight %}
  211. 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`).
  212. {% highlight css %}
  213. .white-popup {
  214. position: relative;
  215. background: #FFF;
  216. padding: 20px;
  217. width: auto;
  218. max-width: 500px;
  219. margin: 20px auto;
  220. }
  221. {% endhighlight %}
  222. 3) Add button that will open the popup (source must match CSS id of an element (`#test-popup` in our case).
  223. {% highlight html %}
  224. <!-- Like so: -->
  225. <a href="#test-popup" class="open-popup-link">Show inline popup</a>
  226. <!-- Or like so: -->
  227. <a href="mobile-friendly-page.html" data-mfp-src="#test-popup" class="open-popup-link">Show inline popup</a>
  228. {% endhighlight %}
  229. 4) Initialize script.
  230. {% highlight javascript %}
  231. $('.open-popup-link').magnificPopup({
  232. type:'inline',
  233. midClick: true // Allow opening popup on middle mouse click. Always set it to true if you don't provide alternative source in href.
  234. });
  235. {% endhighlight %}
  236. Here are some other ways to initialize popup:
  237. {% highlight javascript %}
  238. // From HTML string
  239. $('button').magnificPopup({
  240. items: {
  241. src: '<div class="white-popup">Dynamically created popup</div>',
  242. type: 'inline'
  243. }
  244. });
  245. // From an element with ID #popup
  246. $('button').magnificPopup({
  247. items: {
  248. src: '#popup',
  249. type: 'inline'
  250. }
  251. });
  252. // From jQuery object
  253. $('button').magnificPopup({
  254. items: {
  255. src: $('<div class="white-popup">Dynamically created popup</div>'),
  256. type: 'inline'
  257. }
  258. });
  259. // Open directly via API
  260. $.magnificPopup.open({
  261. items: {
  262. src: '<div class="white-popup">Dynamically created popup</div>', // can be a HTML string, jQuery object, or CSS selector
  263. type: 'inline'
  264. }
  265. });
  266. {% endhighlight %}
  267. I have created two examples on CodePen that will help you better understand how it works:
  268. - [Simple inline popup](http://codepen.io/dimsemenov/pen/GEKgb)
  269. - [Advanced popup with markup and gallery mode](http://codepen.io/dimsemenov/pen/sHoxp)
  270. ## Ajax Type
  271. 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).
  272. **Important note!** The contents of the file that you load is already a popup itself, so there must be **only one root element**.
  273. {% highlight html %}
  274. <a href="path-to-file.html" class="ajax-popup-link">Show inline popup</a>
  275. {% endhighlight %}
  276. {% highlight javascript %}
  277. $('.ajax-popup-link').magnificPopup({
  278. type: 'ajax'
  279. });
  280. {% endhighlight %}
  281. 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).
  282. Ajax options:
  283. {% highlight javascript %}
  284. ajax: {
  285. settings: null, // Ajax settings object that will extend default one - http://api.jquery.com/jQuery.ajax/#jQuery-ajax-settings
  286. // For example:
  287. // settings: {cache:false, async:false}
  288. cursor: 'mfp-ajax-cur', // CSS class that will be added to body during the loading (adds "progress" cursor)
  289. tError: '<a href="%url%">The content</a> could not be loaded.' // Error message, can contain %curr% and %total% tags if gallery is enabled
  290. }
  291. {% endhighlight %}
  292. To modify content after it's loaded, or to select and show just specific element from loaded file, there is a `parseAjax` callback:
  293. {% highlight javascript %}
  294. callbacks: {
  295. parseAjax: function(mfpResponse) {
  296. // mfpResponse.data is a "data" object from ajax "success" callback
  297. // for simple HTML file, it will be just String
  298. // You may modify it to change contents of the popup
  299. // For example, to show just #some-element:
  300. // mfpResponse.data = $(mfpResponse.data).find('#some-element');
  301. // mfpResponse.data must be a String or a DOM (jQuery) element
  302. console.log('Ajax content loaded:', mfpResponse);
  303. },
  304. ajaxContentAdded: function() {
  305. // Ajax content is loaded and appended to DOM
  306. console.log(this.content);
  307. }
  308. }
  309. {% endhighlight %}
  310. ## Options
  311. Options should be passed to the initialization code and separated by comma, e.g.:
  312. {% highlight javascript %}
  313. $('.some-link').magnificPopup({
  314. // main options
  315. disableOn: 400,
  316. key: 'some-key',
  317. gallery: {
  318. // options for gallery
  319. enabled: true
  320. },
  321. image: {
  322. // options for image content type
  323. titleSrc: 'title'
  324. }
  325. });
  326. {% endhighlight %}
  327. Options for specific modules are explained in their sections of documentation (e.g. related to text are in <a href="#translating">translating section</a>, related to gallery are in <a href="#gallery">gallery section</a>. Here you can find the list of general options:
  328. ### disableOn
  329. <code class="def">null</code>
  330. If window width is less then number in this option - lightbox will not be opened and default behavior of element will be triggered. Set to `0` to disable behavior. Option works only when you initialize Magnific Popup from DOM element.
  331. Can also accept Function as a parameter, which should return `true` if lightbox can be opened and `false` otherwise. For example:
  332. {% highlight javascript %}
  333. disableOn: function() {
  334. if( $(window).width() < 600 ) {
  335. return false;
  336. }
  337. return true;
  338. }
  339. {% endhighlight %}
  340. ### key
  341. <code class="def">null</code>
  342. "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.
  343. 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).
  344. 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.
  345. You can delete cached templates like so:
  346. // delete template with key "your-key"
  347. delete $.magnificPopup.instance.popupsCache['your-key'];
  348. // delete all templates
  349. $.magnificPopup.instance.popupsCache = {};
  350. ### midClick
  351. <code class="def">false</code>
  352. 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.
  353. ### mainClass
  354. <code class="def">empty string</code>
  355. 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 myClasTwo'`.
  356. ### preloader
  357. <code class="def">true</code>
  358. 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:
  359. {% highlight css %}
  360. /* Content loading is in progress */
  361. .mfp-s-loading { }
  362. /* Content successfully loaded */
  363. .mfp-s-ready { }
  364. /* Error during loading */
  365. .mfp-s-error { }
  366. {% endhighlight %}
  367. For example, if you want your error message to be in red add such CSS:
  368. {% highlight css %}
  369. .mfp-s-error .mfp-preloader {
  370. color: red;
  371. }
  372. {% endhighlight %}
  373. You can trigger change of status manually by calling `instance.updateStatus('error', 'error message')`.
  374. ### focus
  375. <code class="def">empty string</code>
  376. 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.
  377. ### closeOnContentClick
  378. <code class="def">false</code>
  379. Close popup when user clicks on content of it. It's recommended to enable this option when you have only image in popup.
  380. ### closeOnBgClick
  381. <code class="def">true</code>
  382. Close the popup when user clicks on the dark overlay.
  383. ### closeBtnInside
  384. <code class="def">false</code>
  385. 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` will be replaced with this button, otherwise close button will be appended directly.
  386. ### showCloseBtn
  387. <code class="def">true</code>
  388. Controls whether the close button will be displayed or not.
  389. ### enableEscapeKey
  390. <code class="def">true</code>
  391. Controls whether pressing the escape key will dismiss the active popup or
  392. not.
  393. ### modal
  394. <code class="def">false</code>
  395. When set to `true`, the popup will have a modal-like behavior: it won't be
  396. possible to dismiss it by usual means (close button, escape key, or
  397. clicking in the overlay).
  398. This is is a shortcut to set ``closeOnContentClick``, ``closeOnBgClick``,
  399. ``showCloseBtn``, and ``enableEscapeKey`` to ``false``.
  400. ### alignTop
  401. <code class="def">false</code>
  402. 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).
  403. ### fixedContentPos
  404. <code class="def">auto</code>
  405. 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.
  406. ### fixedBgPos
  407. <code class="def">auto</code>
  408. 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.
  409. ### overflowY
  410. <code class="def">auto</code>
  411. Defines scrollbar of the popup, works as overflow-y CSS property - any <a href="https://developer.mozilla.org/en-US/docs/CSS/overflow-y">CSS acceptable value</a> is allowed (e.g. `auto`, `scroll`, `hidden`). Option is applied only when fixed position is enabled.
  412. There is no option `overflowX`, but you may easily emulate it just via CSS.
  413. ### removalDelay
  414. <code class="def">0</code>
  415. Delay before popup is removed from DOM. Used for the [animation](#animation).
  416. ### closeMarkup
  417. <code class="def">&lt;button title=&quot;%title%&quot; class=&quot;mfp-close&quot;&gt;&lt;i class=&quot;mfp-close-icn&quot;&gt;&amp;times;&lt;/i&gt;&lt;/button&gt;</code>
  418. Markup of close button. %title% will be replaced with option `tClose`.
  419. ### prependTo
  420. <code class="def">document.body</code>
  421. 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.
  422. ## Gallery
  423. Basically all galery module does is allows you to switch content of popup and adds navigation arrows. It can switch and mix any types of content, not just images. Gallery options:
  424. {% highlight javascript %}
  425. gallery: {
  426. enabled: false, // set to true to enable gallery
  427. preload: [0,2], // read about this option in next Lazy-loading section
  428. navigateByImgClick: true,
  429. arrowMarkup: '<button title="%title%" type="button" class="mfp-arrow mfp-arrow-%dir%"></button>', // markup of an arrow button
  430. tPrev: 'Previous (Left arrow key)', // title for left button
  431. tNext: 'Next (Right arrow key)', // title for right button
  432. tCounter: '<span class="mfp-counter">%curr% of %total%</span>' // markup of counter
  433. }
  434. {% endhighlight %}
  435. Example:
  436. {% highlight javascript %}
  437. // This will create a single gallery from all elements that have class "gallery-item"
  438. $('.gallery-item').magnificPopup({
  439. type: 'image',
  440. gallery:{
  441. enabled:true
  442. }
  443. });
  444. {% endhighlight %}
  445. ### Multiple galleries
  446. To have multiple galleries on a page, you need to create a new instance of Magnific Popup for each seperate gallery. For example
  447. {% highlight html %}
  448. <div class="gallery">
  449. <a href="path-to-image.jpg">Open image 1 (gallery #1)</a>
  450. <a href="path-to-image.jpg">Open image 2 (gallery #1)</a>
  451. </div>
  452. <div class="gallery">
  453. <a href="path-to-image.jpg">Open image 1 (gallery #2)</a>
  454. <a href="path-to-image.jpg">Open image 2 (gallery #2)</a>
  455. <a href="http://vimeo.com/123123" class="mfp-iframe">Open video (gallery #2). Class mfp-iframe forces "iframe" content type on this item.</a>
  456. </div>
  457. {% endhighlight %}
  458. {% highlight javascript %}
  459. $('.gallery').each(function() { // the containers for all your galleries
  460. $(this).magnificPopup({
  461. delegate: 'a', // the selector for gallery item
  462. type: 'image',
  463. gallery: {
  464. enabled:true
  465. }
  466. });
  467. });
  468. {% endhighlight %}
  469. You don't necessarily need to use `delegate` option, it can be just `$(this).find('a').magnificPopup( ...`.
  470. ### Lazy-loading
  471. Lazy-loading option preloads nearby items. It accepts array with two integers, first one - is a number of items to preload before the current, second one - the number of images to preload after the current. For example `preload: [1,3]` will load 3 next items and 1 that is before current. These values are automatically switched based on direction of movement.
  472. By default all what it does is just searches for an image tag and preloads it with JavaScript. But you can extend it and do your custom preloading logic with help of `lazyLoad` event, like so:
  473. {% highlight javascript %}
  474. callbacks: {
  475. lazyLoad: function(item) {
  476. console.log(item); // Magnific Popup data object that should be loaded
  477. }
  478. }
  479. {% endhighlight %}
  480. "Preload" option can be changed dynamically. To disable it set `preload:0`.
  481. ## Animation
  482. Animation can be added to any example. For Ajax based popup content animation is fired only after content is loaded.
  483. After popup is opened popup wrapper and background overlay get class `mfp-ready`. Before popup is removed they get class `mfp-removing`.
  484. For example:
  485. {% highlight javascript %}
  486. // Initialize popup as usual
  487. $('.popup-link').magnificPopup({
  488. // Delay in milliseconds before popup is removed
  489. removalDelay: 300,
  490. // Class that is added to popup wrapper and background
  491. // make it unique to apply your CSS animations just to this exact popup
  492. mainClass: 'mfp-fade'
  493. });
  494. {% endhighlight %}
  495. Then just play with CSS3 transitions:
  496. {% highlight css %}
  497. /* overlay at start */
  498. .mfp-fade.mfp-bg {
  499. opacity: 0;
  500. -webkit-transition: all 0.15s ease-out;
  501. -moz-transition: all 0.15s ease-out;
  502. transition: all 0.15s ease-out;
  503. }
  504. /* overlay animate in */
  505. .mfp-fade.mfp-bg.mfp-ready {
  506. opacity: 0.8;
  507. }
  508. /* overlay animate out */
  509. .mfp-fade.mfp-bg.mfp-removing {
  510. opacity: 0;
  511. }
  512. /* content at start */
  513. .mfp-fade.mfp-wrap .mfp-content {
  514. opacity: 0;
  515. -webkit-transition: all 0.15s ease-out;
  516. -moz-transition: all 0.15s ease-out;
  517. transition: all 0.15s ease-out;
  518. }
  519. /* content animate it */
  520. .mfp-fade.mfp-wrap.mfp-ready .mfp-content {
  521. opacity: 1;
  522. }
  523. /* content animate out */
  524. .mfp-fade.mfp-wrap.mfp-removing .mfp-content {
  525. opacity: 0;
  526. }
  527. {% endhighlight %}
  528. Please use animation wisely and when it's really required. Do not enable it when your popup may contain large image or a lot of HTML text.
  529. ## Retina
  530. "Retina" module allows you to display high-resolution images on high-dpi screens with different `devicePixelRatio`. Module works only with "image" type and only when `window.devicePixelRatio > 1`.
  531. First of prepare two sets of images. Default supported syntax requires `@2x` at the end of the image file name, e.g.: `image.jpg` > `image@2x.jpg`. Then initialize popup as usual and add `ratio` in retina set of options.
  532. {% highlight html %}
  533. <a href="image.jpg" class="image-link">Open popup</a>
  534. {% endhighlight %}
  535. {% highlight javascript %}
  536. // Initialize popup as usual
  537. $('.image-link').magnificPopup({
  538. type: 'image',
  539. retina: {
  540. ratio: 1, // Increase this number to enable retina image support.
  541. // Image in popup will be scaled down by this number.
  542. // Option can also be a function which should return a number (in case you support multiple ratios). For example:
  543. // ratio: function() { return window.devicePixelRatio === 1.5 ? 1.5 : 2 }
  544. replaceSrc: function(item, ratio) {
  545. return item.src.replace(/\.\w+$/, function(m) { return '@2x' + m; });
  546. } // function that changes image source
  547. }
  548. });
  549. {% endhighlight %}
  550. View [example of retina popup on CodePen](http://codepen.io/dimsemenov/pen/Dohka).
  551. ## Zoom effect
  552. Zooming only works for images, for now. To add zooming effect, first of make sure that you included "zoom" module to Magnific Popup build (since v0.9.1.). Then follow steps:
  553. 1) Add the thumbnail with link that will open the popup, for example:
  554. {% highlight html %}
  555. <a href="image.jpg" class="image-link">
  556. <img src="thumbnails.jpg" />
  557. </a>
  558. {% endhighlight %}
  559. You need to make sure that ratio of your thumbnail matches the ratio of the big image, to avoid "jumps" at the end of zoom-out animation.
  560. 2) Initialize popup with `zoom` options:
  561. {% highlight javascript %}
  562. // Initialize popup as usual
  563. $('.image-link').magnificPopup({
  564. type: 'image',
  565. mainClass: 'mfp-with-zoom', // this class is for CSS animation below
  566. zoom: {
  567. enabled: true, // By default it's false, so don't forget to enable it
  568. duration: 300, // duration of the effect, in milliseconds
  569. easing: 'ease-in-out', // CSS transition easing function
  570. // The "opener" function should return the element from which popup will be zoomed in
  571. // and to which popup will be scaled down
  572. // By defailt it looks for an image tag:
  573. opener: function(openerElement) {
  574. // openerElement is the element on which popup was initialized, in this case its <a> tag
  575. // you don't need to add "opener" option if this code matches your needs, it's defailt one.
  576. return openerElement.is('img') ? openerElement : openerElement.find('img');
  577. }
  578. }
  579. });
  580. {% endhighlight %}
  581. 3) Optionally, add CSS fading animation to background overlay
  582. {% highlight css %}
  583. .mfp-with-zoom .mfp-container,
  584. .mfp-with-zoom.mfp-bg {
  585. opacity: 0;
  586. -webkit-backface-visibility: hidden;
  587. /* ideally, transition speed should match zoom duration */
  588. -webkit-transition: all 0.3s ease-out;
  589. -moz-transition: all 0.3s ease-out;
  590. -o-transition: all 0.3s ease-out;
  591. transition: all 0.3s ease-out;
  592. }
  593. .mfp-with-zoom.mfp-ready .mfp-container {
  594. opacity: 1;
  595. }
  596. .mfp-with-zoom.mfp-ready.mfp-bg {
  597. opacity: 0.8;
  598. }
  599. .mfp-with-zoom.mfp-removing .mfp-container,
  600. .mfp-with-zoom.mfp-removing.mfp-bg {
  601. opacity: 0;
  602. }
  603. {% endhighlight %}
  604. Zoom module adds `zoomAnimationEnded` callback, which fires when zoom-in animation is finished.
  605. ## API
  606. There is a much bigger list of public events, methods and variables than provided here which is used for module development, look inside code or type in console `$.magnificPopup.instance.` to find them, if you think that something should be added to docs - please submit commit.
  607. ### Events
  608. You can define callbacks in `callbacks` option. Besides that, all Magnific Popup events are also dispatched using `triggerHandler` on target element (or to document if the element doesn't exist).
  609. {% highlight javascript %}
  610. $('.image-link').magnificPopup({
  611. // you may add other options here, e.g.:
  612. preloader: true,
  613. callbacks: {
  614. open: function() {
  615. // Will fire when this exact popup is opened
  616. // this - is Magnific Popup object
  617. },
  618. close: function() {
  619. // Will fire when popup is closed
  620. }
  621. // e.t.c.
  622. }
  623. });
  624. // Alternative method: using events
  625. // Name of event should start from `mfp` and the first letter should be uppercase.
  626. // e.g. 'open' becomes 'mfpOpen', 'beforeOpen' becomes 'mfpBeforeOpen'.
  627. $('.image-link').on('mfpOpen', function(e /*, params */) {
  628. console.log('Popup opened', $.magnificPopup.instance);
  629. });
  630. {% endhighlight %}
  631. List of callbacks. In each callback `this` is `$.magnificPopup.instance`, so you can execute methods (`this.close()`) or access public variables (`this.currItem`).
  632. {% highlight javascript %}
  633. callbacks: {
  634. beforeOpen: function() {
  635. console.log('Start of popup initialization');
  636. },
  637. elementParse: function(item) {
  638. // Function will fire for each target element
  639. // "item.el" is a target DOM element (if present)
  640. // "item.src" is a source that you may modify
  641. console.log('Parsing content. Item object that is being parsed:', item);
  642. },
  643. change: function() {
  644. console.log('Content changed');
  645. console.log(this.content); // Direct reference to your popup element
  646. },
  647. resize: function() {
  648. console.log('Popup resized');
  649. // resize event triggers only when height is changed or layout forced
  650. },
  651. open: function() {
  652. console.log('Popup is opened');
  653. },
  654. beforeClose: function() {
  655. // Callback available since v0.9.0
  656. console.log('Popup close has been initiated');
  657. },
  658. close: function() {
  659. console.log('Popup removal initiated (after removalDelay timer finished)');
  660. },
  661. afterClose: function() {
  662. console.log('Popup is completely closed');
  663. },
  664. markupParse: function(template, values, item) {
  665. // Triggers each time when content of popup changes
  666. // console.log('Parsing:', template, values, item);
  667. },
  668. updateStatus: function(data) {
  669. console.log('Status changed', data);
  670. // "data" is an object that has two properties:
  671. // "data.status" - current status type, can be "loading", "error", "ready"
  672. // "data.text" - text that will be displayed (e.g. "Loading...")
  673. // you may modify this properties to change current status or its text dynamically
  674. },
  675. imageLoadComplete: function() {
  676. // fires when image in current popup finished loading
  677. // avaiable since v0.9.0
  678. console.log('Image loaded');
  679. },
  680. // Only for ajax popup type
  681. parseAjax: function(mfpResponse) {
  682. // mfpResponse.data is a "data" object from ajax "success" callback
  683. // for simple HTML file, it will be just String
  684. // You may modify it to change contents of the popup
  685. // For example, to show just #some-element:
  686. // mfpResponse.data = $(mfpResponse.data).find('#some-element');
  687. // mfpResponse.data must be a String or a DOM (jQuery) element
  688. console.log('Ajax content loaded:', mfpResponse);
  689. },
  690. ajaxContentAdded: function() {
  691. // Ajax content is loaded and appended to DOM
  692. console.log(this.content);
  693. }
  694. }
  695. {% endhighlight %}
  696. ### Public methods
  697. {% highlight javascript %}
  698. // Open popup immediately. If popup is already opened - it'll just overwite the content (but old options will be kept).
  699. // - first parameter: options object
  700. // - second parameter (optional): index of item to open
  701. $.magnificPopup.open({
  702. items: {
  703. src: 'someimage.jpg'
  704. },
  705. type: 'image'
  706. // You may add options here, they're exactly the same as for $.fn.magnificPopup call
  707. // Note that some settings that rely on click event (like disableOn or midClick) will not work here
  708. }, 0);
  709. $.magnificPopup.close(); // Close popup that is currently opened (shorthand)
  710. /*
  711. Methods below don't have shorthand like "open" and "close".
  712. They should be called through "instance" object.
  713. "instance" is available only when at least one popup was opened.
  714. For example: $.magnificPopup.instance.doSomething();
  715. */
  716. var magnificPopup = $.magnificPopup.instance; // save instance in magnificPopup variable
  717. magnificPopup.close(); // Close popup that is currently opened
  718. // Navigation when gallery is enabled
  719. magnificPopup.next(); // go to next item
  720. magnificPopup.prev(); // go to prev item
  721. magnificPopup.goTo(4); // go to item #4
  722. magnificPopup.updateItemHTML(); // updates the popup content. Useful after you change "items" array
  723. // Update status of popup
  724. // First param: status type, can be: 'loading', 'error' or 'ready'.
  725. // Second param: message that will be displayed.
  726. magnificPopup.updateStatus('loading', 'The loading text...');
  727. {% endhighlight %}
  728. You may also call ANY method via `$.fn.magnificPopup('methodName' /*, param1, param2 ... */)` after you initialized the popup, for example:
  729. {% highlight javascript %}
  730. // First of make sure that you initialized popup on element $('.element-with-popup')
  731. // Then
  732. $('.element-with-popup').magnificPopup('open'); // Will open the popup
  733. $('.element-with-popup').magnificPopup('open', 5); // Will open popup with 5th item
  734. $('.element-with-popup').magnificPopup('next');
  735. $('.element-with-popup').magnificPopup('goTo', 3);
  736. {% endhighlight %}
  737. You may also open the popup directly at initialization:
  738. {% highlight javascript %}
  739. $('.element-with-popup').magnificPopup({
  740. items: {
  741. src: 'path-to-image.jpg',
  742. type: 'image'
  743. }
  744. // (optionally) other options
  745. }).magnificPopup('open');
  746. {% endhighlight %}
  747. ### Public properties
  748. Most properties are available only after the popup is opened. Only most used are listed here.
  749. {% highlight javascript %}
  750. var magnificPopup = $.magnificPopup.instance;
  751. magnificPopup.items // array that holds data for popup items
  752. magnificPopup.currItem // data for current item
  753. magnificPopup.index // current item index (integer)
  754. magnificPopup.content // direct reference to jQuery DOM element that you open in popup
  755. magnificPopup.bgOverlay // transluscent overlay
  756. magnificPopup.wrap // container that holds all controls and contentContainer
  757. magnificPopup.contentContainer // container that holds popup content, child of wrap
  758. magnificPopup.st.el // Target clicked element that opened popup (works if popup is initialized from DOM element)
  759. magnificPopup.st.mainEl // Main element (or collection of elements) from which popup was initialized (--''--)
  760. magnificPopup.isIE7
  761. magnificPopup.isIOS
  762. {% endhighlight %}
  763. ## Translating
  764. Internationalization of Magnific Popup is very simple, all you need is to extend default settings object with new values, or just pass options to your initialization code. If you're making some public plugin or theme, it's strongly recommended to use only second method to avoid conflicts.
  765. Some properties contain %keys% that should not be translated, but may be reordered or removed.
  766. {% highlight javascript %}
  767. // Add it after jquery.magnific-popup.js and before first initialization code
  768. $.extend(true, $.magnificPopup.defaults, {
  769. tClose: 'Close (Esc)', // Alt text on close button
  770. tLoading: 'Loading...', // Text that is displayed during loading. Can contain %curr% and %total% keys
  771. gallery: {
  772. tPrev: 'Previous (Left arrow key)', // Alt text on left arrow
  773. tNext: 'Next (Right arrow key)', // Alt text on right arrow
  774. tCounter: '%curr% of %total%' // Markup for "1 of 7" counter
  775. },
  776. image: {
  777. tError: '<a href="%url%">The image</a> could not be loaded.' // Error message when image could not be loaded
  778. },
  779. ajax: {
  780. tError: '<a href="%url%">The content</a> could not be loaded.' // Error message when ajax request failed
  781. }
  782. });
  783. {% endhighlight %}
  784. Same thing, but applied only to specific slider:
  785. {% highlight javascript %}
  786. $('.some-button').magnificPopup({
  787. tClose: 'Close (Esc)',
  788. tLoading: 'Loading...',
  789. gallery: {
  790. tPrev: 'Previous (Left arrow key)',
  791. tNext: 'Next (Right arrow key)',
  792. tCounter: '%curr% of %total%'
  793. },
  794. image: {
  795. tError: '<a href="%url%">The image</a> could not be loaded.'
  796. },
  797. ajax: {
  798. tError: '<a href="%url%">The request</a> failed.'
  799. }
  800. // surely, you may add other options here
  801. });
  802. {% endhighlight %}
  803. ## FAQ
  804. ### How to place gallery navigation arrows "inside" the image?
  805. See [example on CodePen](http://codepen.io/dimsemenov/pen/JGjHK).
  806. ### How to override some function without modifying the source files?
  807. Rewrite the function that you wish to modify by editing Magnific Popup object, you can access it like so `$.magnificPopup.instance`. For example to override function that goes to "next" item in gallery:
  808. {% highlight javascript %}
  809. // add this code after popup JS file is included
  810. $.magnificPopup.instance.next = function() {
  811. // Do something
  812. // You may call parent ("original") method like so:
  813. $.magnificPopup.proto.next.call(this /*, optional arguments */);
  814. };
  815. {% endhighlight %}
  816. You may override any public function, just note that this change applies globally.
  817. ### How to add spinner indicator instead of "Loading..." text?
  818. Just style element with class `.mfp-preloader`. [Example on CodePen](http://codepen.io/dimsemenov/pen/aKwxt). [Another example](http://codepen.io/dimsemenov/pen/HdjtL) (if you want to show image only after its fully loaded).
  819. ## Known issues
  820. ### When popup is opened scrollbar of window disappears and creates empty space or shifts some fixed-positioned menu (or whatever)
  821. Solution 1: add [overflowY:'scroll'](#overflowy) option to force the scrollbar. Solution 2: use open/close popup callbacks to apply custom styling to menu that behaves incorrectly.
  822. ### Text input in [Select2](http://ivaynberg.github.io/select2/) plugin is inactive when added inside popup
  823. Refer to [this discussion on GitHub](https://github.com/dimsemenov/Magnific-Popup/issues/280).
  824. <h2 id="contribute">Make Magnific Popup better!</h2>
  825. Improve this documentation page (simply submit commit <a href="https://github.com/dimsemenov/Magnific-Popup/edit/master/website/documentation.md">via GitHub</a>). Any improvements, including your own CodePen examples are very welcome. And, lastly, don't forget to star the script on GitHub:
  826. <div>
  827. <iframe src="http://ghbtns.com/github-btn.html?user=dimsemenov&amp;repo=magnific-popup&amp;type=watch&amp;count=true&amp;size=large" allowtransparency="true" frameborder="0" scrolling="0" width="170" height="30">&nbsp;</iframe>
  828. </div>