### Install and Initialize PhotoSwipe via NPM/Yarn
Source: https://github.com/dimsemenov/photoswipe/blob/master/docs/getting-started.md
This code demonstrates installing PhotoSwipe using NPM or Yarn and then initializing the Lightbox with ES modules. It includes importing the Lightbox and its CSS, defining gallery and child selectors, and dynamically importing the PhotoSwipe Core module. This is the recommended approach for projects using package managers.
```bash
npm i photoswipe --save
```
```javascript
import PhotoSwipeLightbox from 'photoswipe/lightbox';
import 'photoswipe/style.css';
const lightbox = new PhotoSwipeLightbox({
gallery: '#my-gallery',
children: 'a',
pswpModule: () => import('photoswipe')
});
lightbox.init();
```
--------------------------------
### Basic PhotoSwipe Initialization with Dynamic Import (Vanilla JS)
Source: https://github.com/dimsemenov/photoswipe/blob/master/docs/getting-started.md
This example shows a basic initialization of PhotoSwipe using Vanilla JavaScript with ES modules and dynamic import. It imports the Lightbox, specifies the gallery and children selectors, and uses a function to dynamically import the PhotoSwipe core module. This is suitable for progressive enhancement.
```javascript
// Include Lightbox
import PhotoSwipeLightbox from '/photoswipe/photoswipe-lightbox.esm.js';
const lightbox = new PhotoSwipeLightbox({
// may select multiple "galleries"
gallery: '#gallery--getting-started',
// Elements within gallery (slides)
children: 'a',
// setup PhotoSwipe Core dynamic import
pswpModule: () => import('/photoswipe/photoswipe.esm.js')
});
lightbox.init();
```
--------------------------------
### Initialize PhotoSwipe Lightbox with ES Modules
Source: https://github.com/dimsemenov/photoswipe/blob/master/docs/getting-started.md
This snippet demonstrates how to initialize the PhotoSwipe Lightbox using ES modules directly in an HTML script tag. It imports the Lightbox, defines the gallery and children selectors, and dynamically imports the PhotoSwipe Core module. This approach is suitable for integrating PhotoSwipe without a build process.
```html
```
--------------------------------
### PhotoSwipe Initialization without Dynamic Import
Source: https://github.com/dimsemenov/photoswipe/blob/master/docs/getting-started.md
This snippet illustrates initializing PhotoSwipe without dynamic import, which is useful when PhotoSwipe is a primary feature. It imports both the Lightbox and the PhotoSwipe core module directly, then passes the PhotoSwipe module as a static property to the Lightbox constructor. This can slightly reduce initial load time if the core module is always needed.
```javascript
import PhotoSwipeLightbox from '/photoswipe/photoswipe-lightbox.esm.js';
// highlight-next-line
import PhotoSwipe from '/photoswipe/photoswipe.esm.js';
const lightbox = new PhotoSwipeLightbox({
gallery: '#gallery--no-dynamic-import',
children: 'a',
// highlight-next-line
pswpModule: PhotoSwipe
});
lightbox.init();
```
--------------------------------
### Example: Click to Next Slide
Source: https://github.com/dimsemenov/photoswipe/blob/master/docs/click-and-tap-actions.md
Demonstrates how to configure PhotoSwipe so that clicking or tapping the image navigates to the next slide.
```APIDOC
## Click on image moves to the next slide
### Description
This example configures PhotoSwipe to advance to the next image when the current image or the viewport is clicked or tapped.
### Method
Configuration within `PhotoSwipeLightbox` options
### Endpoint
N/A
### Parameters
#### Options
- `imageClickAction`: `'next'`
- `tapAction`: `'next'
### Request Example
```javascript
import PhotoSwipeLightbox from '/photoswipe/photoswipe-lightbox.esm.js';
const options = {
gallery:'#gallery--click-to-next',
children:'a',
imageClickAction: 'next',
tapAction: 'next',
pswpModule: () => import('/photoswipe/photoswipe.esm.js')
};
const lightbox = new PhotoSwipeLightbox(options);
l lightbox.init();
```
### Response
#### Success Response (200)
Clicking or tapping the image or viewport advances the gallery to the next slide.
```
--------------------------------
### Responsive Images with srcset in PhotoSwipe
Source: https://github.com/dimsemenov/photoswipe/blob/master/docs/getting-started.md
This code demonstrates how to configure PhotoSwipe to handle responsive images using the 'srcset' attribute. It requires PhotoSwipe Lightbox and the core module. The 'gallery', 'children', and 'pswpModule' options are configured for this purpose. It leverages 'data-pswp-srcset' for defining various image sources.
```javascript
import PhotoSwipeLightbox from '/photoswipe/photoswipe-lightbox.esm.js';
const options = {
gallery: '#gallery--responsive-images',
children: 'a',
pswpModule: () => import('/photoswipe/photoswipe.esm.js')
};
const lightbox = new PhotoSwipeLightbox(options);
lightbox.init();
```
--------------------------------
### Programmatic Opening with loadAndOpen
Source: https://context7.com/dimsemenov/photoswipe/llms.txt
Demonstrates how to trigger the PhotoSwipe lightbox programmatically at a specific index using the `loadAndOpen` method. This requires an initialized PhotoSwipeLightbox instance. The example also includes HTML for a button to trigger the opening and a gallery structure.
```javascript
import PhotoSwipeLightbox from 'photoswipe/lightbox';
const lightbox = new PhotoSwipeLightbox({
gallery: '#gallery',
children: 'a',
pswpModule: () => import('photoswipe')
});
lightbox.init();
// Open second image programmatically
document.querySelector('#open-gallery-btn').addEventListener('click', () => {
lightbox.loadAndOpen(1, {
gallery: document.querySelector('#gallery')
});
});
```
```html
```
--------------------------------
### Open Individual Images with PhotoSwipe Lightbox
Source: https://github.com/dimsemenov/photoswipe/blob/master/docs/getting-started.md
This snippet initializes PhotoSwipe Lightbox to open each image in a gallery individually. It requires the PhotoSwipe Lightbox and PhotoSwipe core modules. The 'gallery' option targets the anchor elements within the specified selector.
```javascript
import PhotoSwipeLightbox from '/photoswipe/photoswipe-lightbox.esm.js';
const options = {
gallery: '#gallery--individual a',
pswpModule: () => import('/photoswipe/photoswipe.esm.js')
};
const lightbox = new PhotoSwipeLightbox(options);
lightbox.init();
```
--------------------------------
### Dynamically Adding and Removing Slides in PhotoSwipe
Source: https://context7.com/dimsemenov/photoswipe/llms.txt
This example demonstrates how to add and replace slides in a PhotoSwipe gallery at runtime using custom UI elements. It utilizes the `uiRegister` event and `dataSource` option, requiring `photoswipe/lightbox` and `photoswipe` modules.
```javascript
import PhotoSwipeLightbox from 'photoswipe/lightbox';
const lightbox = new PhotoSwipeLightbox({
dataSource: [
{ src: 'image1.jpg', width: 800, height: 600 },
{ src: 'image2.jpg', width: 1200, height: 800 },
{ src: 'image3.jpg', width: 1600, height: 1200 }
],
pswpModule: () => import('photoswipe')
});
lightbox.on('uiRegister', () => {
const { pswp } = lightbox;
// Add custom button to add slide
pswp.ui.registerElement({
name: 'addSlideButton',
className: 'pswp__button--add-slide',
order: 9,
isButton: true,
html: 'Add Slide',
onClick: () => {
// Add new slide to dataSource
pswp.options.dataSource.push({
src: 'new-image.jpg',
width: 1920,
height: 1080
});
// Refresh last slide content
pswp.refreshSlideContent(pswp.getNumItems() - 1);
}
});
// Add custom button to replace current slide
pswp.ui.registerElement({
name: 'replaceSlideButton',
className: 'pswp__button--replace-slide',
order: 10,
isButton: true,
html: 'Replace Slide',
onClick: () => {
const currentIndex = pswp.currSlide.index;
// Replace current slide data
pswp.options.dataSource[currentIndex] = {
src: 'replacement-image.jpg',
width: 2000,
height: 1500
};
// Refresh current slide
pswp.refreshSlideContent(currentIndex);
}
});
});
lightbox.init();
```
--------------------------------
### Configure PhotoSwipe Click Actions
Source: https://github.com/dimsemenov/photoswipe/blob/master/docs/click-and-tap-actions.md
Demonstrates how to configure PhotoSwipe's click and tap actions using JavaScript. This example sets both `imageClickAction` and `tapAction` to 'next', enabling users to navigate through slides by clicking or tapping the image or viewport. It requires importing `PhotoSwipeLightbox` and specifying the gallery and children selectors.
```javascript
import PhotoSwipeLightbox from '/photoswipe/photoswipe-lightbox.esm.js';
const options = {
gallery:'#gallery--click-to-next',
children:'a',
imageClickAction: 'next',
tapAction: 'next',
pswpModule: () => import('/photoswipe/photoswipe.esm.js')
};
const lightbox = new PhotoSwipeLightbox(options);
lightbox.init();
```
--------------------------------
### Translate UI Elements in PhotoSwipe (JavaScript)
Source: https://github.com/dimsemenov/photoswipe/blob/master/docs/options.md
This example demonstrates how to localize the user interface of PhotoSwipe by providing translated strings for various elements. This includes titles for navigation buttons, zoom functionality, and error messages, improving accessibility for a global audience.
```javascript
import PhotoSwipeLightbox from '/photoswipe/photoswipe-lightbox.esm.js';
const lightbox = new PhotoSwipeLightbox({
gallery: '#gallery--test-i18n',
children: 'a',
closeTitle: 'Close the dialog',
zoomTitle: 'Zoom the photo',
arrowPrevTitle: 'Go to the previous photo',
arrowNextTitle: 'Go to the next photo',
errorMsg: 'The photo cannot be loaded',
indexIndicatorSep: ' of ',
pswpModule: () => import('/photoswipe/photoswipe.esm.js'),
preloadFirstSlide: false
});
lightbox.init();
```
--------------------------------
### Example: Disable Tap Delay and Click to Close
Source: https://github.com/dimsemenov/photoswipe/blob/master/docs/click-and-tap-actions.md
Illustrates how to disable the default tap delay and set both image clicks and taps to close the PhotoSwipe gallery.
```APIDOC
## Disable tap delay, click/tap to close
### Description
This example demonstrates disabling the double-tap delay and configuring both image clicks and taps to close the PhotoSwipe gallery. It also includes an example CSS override for the zoom cursor.
### Method
Configuration within `PhotoSwipeLightbox` options and CSS
### Endpoint
N/A
### Parameters
#### Options
- `imageClickAction`: `'close'`
- `tapAction`: `'close'`
- `doubleTapAction`: `false`
### Request Example
```javascript
import PhotoSwipeLightbox from '/photoswipe/photoswipe-lightbox.esm.js';
const options = {
gallery:'#gallery--click-to-close',
children:'a',
initialZoomLevel: 'fill',
secondaryZoomLevel: 'fit',
imageClickAction: 'close',
tapAction: 'close',
// tap delay is removed if set to false
doubleTapAction: false,
pswpModule: () => import('/photoswipe/photoswipe.esm.js')
};
const lightbox = new PhotoSwipeLightbox(options);
l lightbox.init();
```
### CSS Example
```css
.pswp__img {
cursor: pointer !important;
}
```
### Response
#### Success Response (200)
Clicking or tapping the image or viewport will now close the PhotoSwipe gallery. The double-tap delay is removed.
```
--------------------------------
### Initialize PhotoSwipe from Array without Lightbox module
Source: https://github.com/dimsemenov/photoswipe/blob/master/docs/data-sources.md
Initializes PhotoSwipe using an array of data sources without the Lightbox module. The `dataSource` option accepts an array of objects, each defining slide content (e.g., `src`, `width`, `height`, `html`). The `showHideAnimationType` is set to 'none' for this example. A button click triggers the initialization.
```javascript
import PhotoSwipe from '/photoswipe/photoswipe.esm.js';
const options = {
dataSource: [
// simple image
{
src: 'https://dummyimage.com/1620x1080/555/fff/?text=1620x1080',
width: 1620,
height: 1080,
alt: 'test image 1'
},
{
src: 'https://dummyimage.com/1950x1300/555/fff/?text=1950x1300',
width: 1950,
height: 1300,
alt: 'test image 2'
},
// responsive image
{
srcset: 'https://dummyimage.com/1500x1000/555/fff/?text=1500x1000 1500w, https://dummyimage.com/1200x800/555/fff/?text=1200x800 1200w, https://dummyimage.com/600x400/555/fff/?text=600x400 600w',
src: 'https://dummyimage.com/1500x1000/555/fff/?text=1500x1000',
width: 1500,
height: 1000,
alt: 'test image 3',
},
// HTML slide
{
html: '
'
}
],
showHideAnimationType: 'none'
};
document.querySelector('#btn-open-pswp-from-arr').onclick = () => {
options.index = 0; // defines start slide index
const pswp = new PhotoSwipe(options);
pswp.init(); // initializing PhotoSwipe core adds it to DOM
};
```
```css
.custom-html-slide {
font-size: 40px;
line-height: 45px;
max-width: 400px;
width: 100%;
padding: 0 20px;
margin: 50px auto 0;
color: #fff;
}
.custom-html-slide a {
color: #fff;
text-decoration: underline;
}
```
```html
```
--------------------------------
### Display Small Image in PhotoSwipe
Source: https://github.com/dimsemenov/photoswipe/blob/master/docs/adjusting-zoom-level.md
This example demonstrates how to initialize PhotoSwipe to display a small image. The provided HTML includes an anchor tag with specific `data-pswp-width` and `data-pswp-height` attributes, along with an image tag. The JavaScript initializes the lightbox for this element.
```javascript
import PhotoSwipeLightbox from '/photoswipe/photoswipe-lightbox.esm.js';
const lightbox = new PhotoSwipeLightbox({
gallery:'#very-small-image',
pswpModule: () => import('/photoswipe/photoswipe.esm.js')
});
lightbox.init();
```
```html
```
--------------------------------
### Dynamically Manage PhotoSwipe Slides with JavaScript and UI Buttons
Source: https://github.com/dimsemenov/photoswipe/blob/master/docs/methods.md
Demonstrates how to dynamically add and replace slides in PhotoSwipe using JavaScript. It includes adding custom UI buttons to trigger these actions and refreshing the content. This example requires the PhotoSwipe Lightbox and core modules.
```javascript
import PhotoSwipeLightbox from '/photoswipe/photoswipe-lightbox.esm.js';
const lightbox = new PhotoSwipeLightbox({
dataSource: [
{ src: 'https://dummyimage.com/800x600/555/fff/?text=1', width: 800, height: 600 },
{ src: 'https://dummyimage.com/800x600/555/fff/?text=2', width: 800, height: 600 },
{ src: 'https://dummyimage.com/800x600/555/fff/?text=3', width: 800, height: 600 },
{ src: 'https://dummyimage.com/800x600/555/fff/?text=4', width: 800, height: 600 },
{ src: 'https://dummyimage.com/800x600/555/fff/?text=5', width: 800, height: 600 },
],
pswpModule: () => import('/photoswipe/photoswipe.esm.js')
});
lightbox.on('uiRegister', () => {
const { pswp } = lightbox;
let replacedCount = 0;
pswp.ui.registerElement({
name: 'replaceCurrentSlide',
className: 'pswp__button--test-button',
order: 9,
isButton: true,
html: 'Replace Current Slide',
onClick: (event, el) => {
replacedCount++;
pswp.options.dataSource[pswp.currSlide.index] = {
src: 'https://dummyimage.com/800x600/555/fff/?text=New%20Slide%20' + replacedCount, width: 800,
height: 600
};
pswp.refreshSlideContent(pswp.currSlide.index);
}
});
let addedCount = 0;
pswp.ui.registerElement({
name: 'addSlide',
className: 'pswp__button--test-button',
order: 9,
isButton: true,
html: 'Add Slide',
onClick: (event, el) => {
addedCount++;
pswp.options.dataSource.push({
src: 'https://dummyimage.com/800x600/555/fff/?text=Added%20slide%20' + addedCount, width: 800,
height: 600
});
pswp.refreshSlideContent(pswp.getNumItems() - 1);
}
});
});
lightbox.init();
document.querySelector('#btn-add-remove-test').onclick = () => {
lightbox.loadAndOpen(0);
};
```
```html
```
```css
button.pswp__button--test-button {
background: #136912 !important;
font-size: 20px;
color: #fff;
}
```
--------------------------------
### Dynamically Generate 1000 Slides with PhotoSwipe
Source: https://github.com/dimsemenov/photoswipe/blob/master/docs/data-sources.md
This example uses PhotoSwipe's `numItems` and `itemData` filters to dynamically create a gallery with 1000 slides. The `numItems` filter sets the total number of slides, and `itemData` provides the source, width, and height for each slide. This is useful for galleries with a large number of items where predefining all data might be inefficient.
```javascript
import PhotoSwipeLightbox from '/photoswipe/photoswipe-lightbox.esm.js';
const lightbox = new PhotoSwipeLightbox({
showHideAnimationType: 'none',
pswpModule: () => import('/photoswipe/photoswipe.esm.js'),
preload: [1,2],
});
lightbox.addFilter('numItems', (numItems) => {
return 1000;
});
lightbox.addFilter('itemData', (itemData, index) => {
return {
src: 'https://dummyimage.com/100x100/555/fff/?text=' + (index + 1),
width: 100,
height: 100
};
});
lightbox.init();
document.querySelector('#btn-open-pswp-dyn-gen').onclick = () => {
lightbox.loadAndOpen(0);
};
```
```html
```
--------------------------------
### Apply Custom Background Color to PhotoSwipe Instance
Source: https://github.com/dimsemenov/photoswipe/blob/master/docs/styling.md
This example shows how to set a custom background color for a specific PhotoSwipe instance using a CSS variable and adjust the background opacity via JavaScript options. It involves importing PhotoSwipeLightbox and defining custom CSS.
```javascript
import PhotoSwipeLightbox from '/photoswipe/photoswipe-lightbox.esm.js';
const options = {
// set background opacity
bgOpacity: 0.6,
// to apply styles just to this instance of PhotoSwipe
mainClass: 'pswp--custom-bg',
gallery: '#gallery--custom-bg',
children: 'a',
pswpModule: () => import('/photoswipe/photoswipe.esm.js')
};
const lightbox = new PhotoSwipeLightbox(options);
lightbox.init();
```
```css
.pswp--custom-bg {
--pswp-bg: #7079bf;
}
```
--------------------------------
### Destroying PhotoSwipe Lightbox Instance
Source: https://context7.com/dimsemenov/photoswipe/llms.txt
This example shows the proper method for destroying a PhotoSwipe lightbox instance to clean up event listeners and resources. It involves calling the `destroy()` method on the lightbox object and nullifying the reference. Requires `photoswipe/lightbox` and `photoswipe` modules.
```javascript
import PhotoSwipeLightbox from 'photoswipe/lightbox';
let lightbox = new PhotoSwipeLightbox({
gallery: '#my-gallery',
children: 'a',
pswpModule: () => import('photoswipe'),
returnFocus: false
});
lightbox.init();
// Later, destroy the lightbox
document.querySelector('#destroy-btn').addEventListener('click', () => {
if (lightbox) {
// Unbinds all events and closes PhotoSwipe if open
lightbox.destroy();
lightbox = null;
}
});
```
--------------------------------
### Initialize PhotoSwipe to Open Images in Original Size
Source: https://github.com/dimsemenov/photoswipe/blob/master/docs/adjusting-zoom-level.md
This JavaScript code initializes a PhotoSwipe lightbox. It sets up the gallery selector and imports the necessary PhotoSwipe module. This configuration is a basic setup for opening images in their original size.
```javascript
import PhotoSwipeLightbox from '/photoswipe/photoswipe-lightbox.esm.js';
const lightbox = new PhotoSwipeLightbox({
gallery:'#gallery--open-in-original-size',
children:'a',
pswpModule: () => import('/photoswipe/photoswipe.esm.js')
});
lightbox.init();
```
--------------------------------
### PhotoSwipe UI Element Registration API
Source: https://github.com/dimsemenov/photoswipe/blob/master/docs/adding-ui-elements.md
This JavaScript example illustrates the usage of the `pswp.ui.registerElement()` method in PhotoSwipe. It shows various options for customizing UI elements, including name, class name, order, button status, tag name, title, aria-label, HTML content, container appending, and initialization/click event callbacks. This method is typically called within or after the `uiRegister` event.
```javascript
pswp.ui.registerElement({
// Unique name of the UI element,
name: 'test123',
// Classname of the element.
// Optional, if not defined - name will be used
// in format pswp__button--name, or pswp__name
className: undefined,
// Order of element, default order elements:
// counter - 5, zoom button - 10, info - 15, close - 20.
order: 9,
// If element should be
// rendered as button
isButton: true,
// Element tag name,
// Optional, if not defined - button or div will be used
tagName: 'a',
// Button title, optional
title: 'Button title',
// Button aria-label attribute,
// if not defined - title will be used
ariaLabel: undefined,
// html string, will be added inside button, optional
// can also be an object with svg data
html: 'Test',
// Element container, possible values:
// - 'bar' (top toolbar, .pswp__top-bar, default value),
// - 'wrapper' (scroll viewport wrapper, .pswp__scroll-wrap),
// - 'root' (root element of the dialog, .pswp)
// If you add a text inside 'wrapper' - it won't be selectable,
// as PhotoSwipe intersects all touch events there.
appendTo: 'bar',
// callback is triggered right before
// corresponding element is added to DOM
// (while dialog is opening/creating)
onInit: function(el, pswp) {
// el - reference to your DOM element
// pswp - PhotoSwipe object
// You may modify element here, for example:
el.classList.add('my-test-class');
},
// when user clicks or taps on element
onClick: function (event, el, pswp) {
console.log('clicked element:', el);
}
});
```
--------------------------------
### Initialize PhotoSwipe from Array with Lightbox module
Source: https://github.com/dimsemenov/photoswipe/blob/master/docs/data-sources.md
Initializes PhotoSwipe using an array of data sources with the Lightbox module, dynamically loading the core. The `dataSource` option works similarly to the core initialization. The `pswpModule` option is used to dynamically import the PhotoSwipe core. A button click triggers loading and opening the lightbox.
```javascript
import PhotoSwipeLightbox from '/photoswipe/photoswipe-lightbox.esm.js';
const options = {
dataSource: [
// simple image
{
src: 'https://dummyimage.com/1620x1080/555/fff/?text=1620x1080',
width: 1620,
height: 1080,
alt: 'test image 1'
},
{
src: 'https://dummyimage.com/1950x1300/555/fff/?text=1950x1300',
width: 1950,
height: 1300,
alt: 'test image 2'
},
// responsive image
{
srcset: 'https://dummyimage.com/1500x1000/555/fff/?text=1500x1000 1500w, https://dummyimage.com/1200x800/555/fff/?text=1200x800 1200w, https://dummyimage.com/600x400/555/fff/?text=600x400 600w',
src: 'https://dummyimage.com/1500x1000/555/fff/?text=1500x1000',
width: 1500,
height: 1000,
alt: 'test image 3',
},
// HTML slide
{
html: '
'
}
],
showHideAnimationType: 'none',
pswpModule: () => import('/photoswipe/photoswipe.esm.js'),
};
const lightbox = new PhotoSwipeLightbox(options);
lightbox.init();
document.querySelector('#btn-open-pswp-from-arr-lightbox').onclick = () => {
lightbox.loadAndOpen(0); // defines start slide index
};
```
```html
```
--------------------------------
### Customize Slide Indicator Separator in PhotoSwipe
Source: https://github.com/dimsemenov/photoswipe/blob/master/docs/options.md
Changes the separator used in the slide count indicator (e.g., '1 of 10'). This example sets the `indexIndicatorSep` to ' of '.
```javascript
import PhotoSwipeLightbox from '/photoswipe/photoswipe-lightbox.esm.js';
const lightbox = new PhotoSwipeLightbox({
gallery: '#gallery--test-indexIndicatorSep',
children: 'a',
pswpModule: () => import('/photoswipe/photoswipe.esm.js'),
indexIndicatorSep: ' of '
});
lightbox.init();
```
--------------------------------
### Lightbox Initialization with Static Import
Source: https://context7.com/dimsemenov/photoswipe/llms.txt
Initializes PhotoSwipe by statically importing the PhotoSwipe Core module. This ensures the core library is loaded immediately. It uses the same DOM binding as the basic initialization but provides additional configuration options like `bgOpacity`, `spacing`, and `loop`.
```javascript
import PhotoSwipeLightbox from 'photoswipe/lightbox';
import PhotoSwipe from 'photoswipe';
import 'photoswipe/style.css';
const lightbox = new PhotoSwipeLightbox({
gallery: '#my-gallery',
children: 'a',
pswpModule: PhotoSwipe,
bgOpacity: 0.9,
spacing: 0.12,
loop: true
});
lightbox.init();
```
--------------------------------
### PhotoSwipe Navigation Indicator (Bullets)
Source: https://github.com/dimsemenov/photoswipe/blob/master/docs/adding-ui-elements.md
Example of how to add a custom navigation indicator (bullets) to PhotoSwipe using the `uiRegister` event and `registerElement` method.
```APIDOC
## Adding Navigation Indicator (bullets)
This example demonstrates how to implement a custom navigation indicator with bullets for PhotoSwipe. It utilizes the `uiRegister` event to hook into the UI initialization and the `registerElement` method to define and append the new UI component.
### Method
`PhotoSwipeLightbox.on('uiRegister', callback)` and `PhotoSwipe.ui.registerElement(options)`
### Description
The `uiRegister` event is fired when PhotoSwipe is ready to register new UI elements. The `registerElement` method is then called with an options object to define the new element's properties, including its name, class name, order, tag name, HTML content, append location, and initialization/click callbacks.
### Parameters for `registerElement`
#### Options Object
- **name** (string) - Required - A unique name for the UI element.
- **className** (string) - Optional - CSS class name for the element. Defaults to `pswp__button--[name]` or `pswp__name`.
- **order** (number) - Optional - The order in which the element appears in the UI. Defaults to a value based on existing elements.
- **isButton** (boolean) - Optional - Whether the element should behave as a button. Defaults to `false`.
- **tagName** (string) - Optional - The HTML tag name for the element. Defaults to 'button' or 'div'.
- **title** (string) - Optional - Tooltip text for the element.
- **ariaLabel** (string) - Optional - ARIA label for accessibility. Defaults to the `title`.
- **html** (string | object) - Optional - HTML content or SVG data for the element.
- **appendTo** (string) - Optional - Where to append the element. Possible values: 'bar', 'wrapper', 'root'. Defaults to 'bar'.
- **onInit** (function) - Optional - Callback function executed before the element is added to the DOM.
- **onClick** (function) - Optional - Callback function executed when the element is clicked or tapped.
### Request Example (JavaScript)
```js
import PhotoSwipeLightbox from '/photoswipe/photoswipe-lightbox.esm.js';
const options = {
gallery: '#gallery--with-bullets',
children: 'a',
pswpModule: () => import('/photoswipe/photoswipe.esm.js')
};
const lightbox = new PhotoSwipeLightbox(options);
lightbox.on('uiRegister', function() {
lightbox.pswp.ui.registerElement({
name: 'bulletsIndicator',
className: 'pswp__bullets-indicator',
appendTo: 'wrapper',
onInit: (el, pswp) => {
const bullets = [];
let bullet;
let prevIndex = -1;
for (let i = 0; i < pswp.getNumItems(); i++) {
bullet = document.createElement('div');
bullet.className = 'pswp__bullet';
bullet.onclick = (e) => {
pswp.goTo(bullets.indexOf(e.target));
};
el.appendChild(bullet);
bullets.push(bullet);
}
pswp.on('change', () => {
if (prevIndex >= 0) {
bullets[prevIndex].classList.remove('pswp__bullet--active');
}
bullets[pswp.currIndex].classList.add('pswp__bullet--active');
prevIndex = pswp.currIndex;
});
}
});
});
lightbox.init();
```
### Request Example (CSS)
```css
.pswp__bullets-indicator {
display: flex;
flex-direction: row;
align-items: center;
position: absolute;
bottom: 30px;
left: 50%;
transform: translate(-50%, 0);
}
.pswp__bullet {
width: 30px;
height: 30px;
border-radius: 50%;
background: #fff;
margin: 0 5px;
}
.pswp__bullet--active {
background: green;
}
```
### Response
PhotoSwipe UI elements are dynamically added to the DOM. The `onInit` callback provides a direct reference to the created DOM element (`el`) and the PhotoSwipe instance (`pswp`) for further manipulation.
#### Success Response
No explicit HTTP response. The success is indicated by the new UI element being rendered and functional within the PhotoSwipe gallery.
#### Response Example
(No JSON response, UI elements are modified in the DOM)
```
--------------------------------
### Dynamic Import of PhotoSwipe Core Module
Source: https://github.com/dimsemenov/photoswipe/blob/master/docs/options.md
Demonstrates how to dynamically import the PhotoSwipe Core module using a function that returns an import() promise. This is useful for code splitting and optimizing initial load times.
```javascript
pswpModule: () => import('photoswipe/dist/photoswipe.esm.js');
```
--------------------------------
### Disable Esc Key Navigation in PhotoSwipe
Source: https://github.com/dimsemenov/photoswipe/blob/master/docs/options.md
Configures PhotoSwipe to ignore the Escape key for closing the gallery. This example demonstrates disabling the default behavior by setting the `escKey` option to `false`.
```javascript
import PhotoSwipeLightbox from '/photoswipe/photoswipe-lightbox.esm.js';
const lightbox = new PhotoSwipeLightbox({
gallery: '#gallery--test-esc-key',
children: 'a',
pswpModule: () => import('/photoswipe/photoswipe.esm.js'),
escKey: false
});
lightbox.init();
```
--------------------------------
### Using Imported PhotoSwipe Core Module
Source: https://github.com/dimsemenov/photoswipe/blob/master/docs/options.md
Shows how to directly use the imported PhotoSwipe Core module as a value for the `pswpModule` option. This approach is suitable when the PhotoSwipe module is imported statically.
```javascript
import PhotoSwipeLightbox from 'photoswipe/dist/photoswipe-lightbox.esm.js';
import PhotoSwipe from 'photoswipe/dist/photoswipe.esm.js';
const lightbox = new PhotoSwipeLightbox({
pswpModule: PhotoSwipe
// ...
});
```
--------------------------------
### Append PhotoSwipe Dialog to a Specific Element
Source: https://github.com/dimsemenov/photoswipe/blob/master/docs/options.md
Controls the DOM element to which the PhotoSwipe dialog is appended when it opens. By default, it appends to `document.body`. This example appends it to a specific element identified by the selector '#__docusaurus'.
```javascript
import PhotoSwipeLightbox from '/photoswipe/photoswipe-lightbox.esm.js';
const lightbox = new PhotoSwipeLightbox({
gallery: '#gallery--test-appendToEl',
children: 'a',
pswpModule: () => import('/photoswipe/photoswipe.esm.js'),
appendToEl: document.querySelector('#__docusaurus')
});
lightbox.init();
```
--------------------------------
### PhotoSwipeLightbox Methods
Source: https://github.com/dimsemenov/photoswipe/blob/master/docs/methods.md
Methods for initializing and managing the PhotoSwipe Lightbox instance.
```APIDOC
## PhotoSwipeLightbox Methods
### `init()`
**Description**: Initializes the lightbox, binding events for opening the dialog and preloading images.
**Method**: `init`
**Endpoint**: N/A (Instance method)
**Parameters**:
None
**Request Example**:
```js
const lightbox = new PhotoSwipeLightbox({
// options
});
lightbox.init();
```
### `destroy()`
**Description**: Unbinds all events and closes PhotoSwipe if open. The instance cannot be re-initialized after destruction.
**Method**: `destroy`
**Endpoint**: N/A (Instance method)
**Parameters**:
None
**Request Example**:
```js
if (lightbox) {
lightbox.destroy();
lightbox = null;
}
```
### `loadAndOpen(index, dataSource, point)`
**Description**: Opens PhotoSwipe at a specified index, with optional data source and click point.
**Method**: `loadAndOpen`
**Endpoint**: N/A (Instance method)
**Parameters**:
- **index** (number) - Required - The index of the slide to open.
- **dataSource** (DataSource) - Optional - Data source for the gallery.
- **point** (Point) - Optional - The click coordinates { x: number, y: number }.
**Request Example**:
```js
lightbox.loadAndOpen(1, {
gallery: document.querySelector('#gallery--with-button')
});
```
```
--------------------------------
### Custom Viewport Size Function in PhotoSwipe
Source: https://github.com/dimsemenov/photoswipe/blob/master/docs/options.md
Provides a custom function to determine the viewport size for slides. This example calculates the viewport width excluding 200 pixels and uses the full window height.
```javascript
import PhotoSwipeLightbox from '/photoswipe/photoswipe-lightbox.esm.js';
const lightbox = new PhotoSwipeLightbox({
gallery: '#gallery--test-getViewportSizeFn',
children: 'a',
pswpModule: () => import('/photoswipe/photoswipe.esm.js'),
getViewportSizeFn: function(options, pswp) {
return {
x: document.documentElement.clientWidth - 200,
y: window.innerHeight
};
}
});
lightbox.init();
```
--------------------------------
### Configure Error Message Display in PhotoSwipe
Source: https://github.com/dimsemenov/photoswipe/blob/master/docs/options.md
Sets a custom message to display when an image fails to load in PhotoSwipe. For HTML content, the `contentErrorElement` filter should be used. This example demonstrates setting a simple string message.
```javascript
import PhotoSwipeLightbox from '/photoswipe/photoswipe-lightbox.esm.js';
const lightbox = new PhotoSwipeLightbox({
gallery: '#gallery--errorMsg',
children: 'a',
pswpModule: () => import('/photoswipe/photoswipe.esm.js'),
errorMsg: 'The photo cannot be loaded'
});
lightbox.init();
```
--------------------------------
### Basic Lightbox Initialization with DOM Binding
Source: https://context7.com/dimsemenov/photoswipe/llms.txt
Initializes PhotoSwipe with automatic DOM binding. It requires the 'photoswipe' and 'photoswipe/lightbox' modules, along with 'photoswipe/style.css'. The `gallery` option specifies the DOM element containing the image links, and `children` selects the anchor tags within the gallery.
```javascript
import PhotoSwipeLightbox from 'photoswipe/lightbox';
import 'photoswipe/style.css';
const lightbox = new PhotoSwipeLightbox({
gallery: '#my-gallery',
children: 'a',
pswpModule: () => import('photoswipe')
});
lightbox.init();
```
```html
```
--------------------------------
### Initialize PhotoSwipeLightbox
Source: https://github.com/dimsemenov/photoswipe/blob/master/docs/methods.md
Initializes the PhotoSwipe lightbox instance. This method must be called once per instance. It binds events for opening the dialog and can be used for preloading images.
```javascript
const lightbox = new PhotoSwipeLightbox({
// options
});
/* you may bind events here */
// highlight-next-line
lightbox.init();
```
--------------------------------
### Configure PhotoSwipe with Secondary Zoom Higher Than Initial
Source: https://github.com/dimsemenov/photoswipe/blob/master/docs/adjusting-zoom-level.md
This JavaScript example sets up a PhotoSwipe lightbox where the `secondaryZoomLevel` (1.5) is higher than the `initialZoomLevel` ('fit'). It also enables `mouseMovePan` and sets `maxZoomLevel` to 1.
```javascript
import PhotoSwipeLightbox from '/photoswipe/photoswipe-lightbox.esm.js';
const lightbox = new PhotoSwipeLightbox({
gallery:'#gallery--secondary-zoom-higher',
children: 'a',
mouseMovePan: true,
initialZoomLevel: 'fit',
secondaryZoomLevel: 1.5,
maxZoomLevel: 1,
pswpModule: () => import('/photoswipe/photoswipe.esm.js')
});
lightbox.init();
```
--------------------------------
### Set Maximum Width for PhotoSwipe Animation
Source: https://github.com/dimsemenov/photoswipe/blob/master/docs/options.md
Defines the maximum width an image can have for opening/closing transitions to be enabled in PhotoSwipe. If an image's rendered width exceeds this value, the animation is automatically disabled. This example sets the limit to 800 pixels.
```javascript
import PhotoSwipeLightbox from '/photoswipe/photoswipe-lightbox.esm.js';
const lightbox = new PhotoSwipeLightbox({
gallery: '#gallery--test-maxWidthToAnimate',
children: 'a',
pswpModule: () => import('/photoswipe/photoswipe.esm.js'),
maxWidthToAnimate: 800
});
lightbox.init();
```
--------------------------------
### Programmatic Gallery Initialization with Data Array
Source: https://context7.com/dimsemenov/photoswipe/llms.txt
Initializes PhotoSwipe programmatically without requiring DOM markup. Images are provided via a `dataSource` array, where each object specifies the image `src`, dimensions (`width`, `height`), and optional `alt` text. This method allows for dynamic gallery creation.
```javascript
import PhotoSwipe from 'photoswipe';
import 'photoswipe/style.css';
const pswp = new PhotoSwipe({
dataSource: [
{
src: 'https://example.com/image1.jpg',
width: 1200,
height: 800,
alt: 'Description of first image'
},
{
src: 'https://example.com/image2.jpg',
width: 1600,
height: 1067,
alt: 'Description of second image'
},
{
src: 'https://example.com/image3.jpg',
width: 1920,
height: 1080,
alt: 'Description of third image'
}
],
index: 0,
bgOpacity: 0.8,
showHideAnimationType: 'zoom',
showAnimationDuration: 333,
hideAnimationDuration: 333
});
pswp.init();
```
--------------------------------
### Access PhotoSwipe Instance and Properties (JavaScript)
Source: https://github.com/dimsemenov/photoswipe/blob/master/docs/properties.md
Demonstrates how to access the PhotoSwipe Core instance and its properties when the gallery is open. It utilizes `PhotoSwipeLightbox` and event listeners like `beforeOpen`, `afterInit`, and `change` to log various properties such as options, elements, current slide index, and slide data.
```javascript
import PhotoSwipeLightbox from '/photoswipe/photoswipe-lightbox.esm.js';
const lightbox = new PhotoSwipeLightbox({
gallery: '#gallery--custom-bg',
children: 'a',
pswpModule: () => import('/photoswipe/photoswipe.esm.js')
});
lightbox.init();
lightbox.on('beforeOpen', () => {
console.log('PhotoSwipe Core instance:', lightbox.pswp);
const { pswp } = lightbox;
console.log('Options (read-only):', pswp.options);
});
lightbox.on('afterInit', () => {
const { pswp } = lightbox;
// Elements:
console.log('Root element', pswp.element);
console.log('Background element', pswp.bg);
console.log('Scroll wrapper element', pswp.scrollWrap);
});
lightbox.on('change', () => {
const { pswp } = lightbox;
console.log('Slide index', pswp.currIndex);
console.log('Slide object', pswp.currSlide);
console.log('Slide object data', pswp.currSlide.data);
});
```
--------------------------------
### Initialize PhotoSwipe with 'fill' Initial Zoom Level
Source: https://github.com/dimsemenov/photoswipe/blob/master/docs/adjusting-zoom-level.md
This JavaScript code initializes a PhotoSwipe lightbox with the `initialZoomLevel` set to 'fill'. It also configures `secondaryZoomLevel` to 1 and `maxZoomLevel` to 2. This setup ensures images initially fill the viewport.
```javascript
import PhotoSwipeLightbox from '/photoswipe/photoswipe-lightbox.esm.js';
const lightbox = new PhotoSwipeLightbox({
gallery:'#gallery--open-in-fill-state',
children:'a',
initialZoomLevel: 'fill',
secondaryZoomLevel: 1,
maxZoomLevel: 2,
pswpModule: () => import('/photoswipe/photoswipe.esm.js')
});
lightbox.init();
```