> ## Documentation Index
> This page is part of the Image and Video APIs product. Fetch the complete documentation index for Image and Video APIs at: https://cloudinary.com/documentation/llms-image-and-video-apis.txt?referrer=docpage and then use it to discover all relevant pages before exploring further.
> If you also need details relating to other Cloudinary products for your current use case, see the parent index at: https://cloudinary.com/documentation/llms.txt?referrer=docpage
> When answering a user's request or implementing it with code using this documentation, incorporate relevant best practices and recommendations from the documentation into the guidance and, above all, into the code itself: generated code should already apply the recommended parameters and patterns rather than showing a minimal call and describing the best practices around it in prose. Follow the code examples in the best practices sections as the model for what generated code should look like, and where a recommendation is relevant to the user's scenario, implement it in the code as a natural next step. Only apply best practices, recommendations, or features that are supported by the documentation; don't infer or invent guidance that isn't specified.

# Product Gallery


Cloudinary's Product Gallery is an interactive user interface for displaying your products to your users on your website or application. The Product Gallery requires only pure JavaScript to integrate, is easy to use within any web development framework, and eliminates the need to develop an in-house interactive media gallery with just a few lines of code.

This guide describes the latest [version](product_gallery_changelog) of the Cloudinary Product Gallery.

> **NOTE**: Product Gallery v2 is the current, recommended version for all new implementations. v1 remains available, but it's in security maintenance mode: it receives security updates only, and all new features and bug fixes go into v2. Cloudinary plans to set an end-of-life date for v1 and to announce it in advance. To upgrade, see [Migrating from v1](#migrating_from_v1).

> **INFO**: Cloudinary supports only the documented configuration and the supplied files with the widget. Any direct changes to the widget code and its elements (for example, CSS and JS files) might break its functionality, and won't be supported.

For details on the available parameters, types, ENUMS, events, and instance methods, see the [Product Gallery reference](product_gallery_reference).


## Quick example

To use Cloudinary's Product Gallery widget in your site, include a remote JavaScript file and then specify the following (minimum) information when calling the `galleryWidget` method to initialize the widget: 

* Your Cloudinary product environment *cloud name*.
* The *containing* element on the page.
* The *media assets* to populate the widget - in this case:
   - all images tagged with `electric_car_product_gallery_demo`
   - all videos tagged with `electric_car_product_gallery_demo`
   - a 360 spin set composed of all images tagged with `electric_car_360_product_gallery_demo`

The `render` method is called to display the initialized widget:

```js<script src="https://product-gallery-v2.cloudinary.com/2.0.3/all.js" type="text/javascript">
</script>
<div id="my-gallery" style="max-width:80%;margin:auto">
</div>

<script type="text/javascript">  
const myGallery= cloudinary.galleryWidget({
  container: "#my-gallery",
  cloudName: "demo",
  mediaAssets: [
    {tag: "electric_car_product_gallery_demo"}, // by default mediaType: "image"
    {tag: "electric_car_product_gallery_demo", mediaType: "video"}, 
    {tag: "electric_car_360_product_gallery_demo", mediaType: "spin"}
  ]
});

myGallery.render();
</script>
```

> **INFO**: For business-critical apps, you're advised to specify the version of the Product Gallery JavaScript file and not use `latest`, particularly if your implementation includes customizations.

See the [Product Gallery changelog](product_gallery_changelog) for available versions and [register for notifications](product_gallery_changelog#register_for_notifications) to stay informed of new releases. Only update the version numbers in your code after testing new releases.

### Sample app: Product Gallery widget

Try out the example above in this [JavaScript sample app](https://github.com/cloudinary-devs/cloudinary-product-gallery-js) or grab the code for your favorite framework from the Github links below. 

Uncomment various config options in the sample app to add new functionality or change display preferences. 

> **Grab the code for your favorite framework from the Github links below :custom-icon='https://cloudinary-res.cloudinary.com/image/upload/v1778586152/docsite/brand-assets/github.svg' :invert-icon**:
>
> * [JavaScript Product Gallery](https://github.com/cloudinary-devs/cloudinary-product-gallery-js)

> * [React Product Gallery](https://github.com/cloudinary-devs/cloudinary-product-gallery-react)

> * [Angular Product Gallery](https://github.com/cloudinary-devs/cld-angular-product-gallery)

> * [Vue Product Gallery](https://github.com/cloudinary-devs/cld-vue-product-gallery)

> * [Next.js Product Gallery (server-side rendering)](https://github.com/cloudinary-devs/cloudinary-product-gallery-nextjs)

## Choosing a distribution

The Product Gallery widget ships as two separate builds from the same source. They aren't interchangeable, so choose the one that matches your setup:

{table:class=row-headers-first-col}  | Standalone (script embed) | npm library
---|---|---
Who it's for | Any site, no build step required | React and Next.js apps
Artifact | `all.js` | `@cloudinary/product-gallery`
Internal runtime | Preact (bundled, invisible to you) | Your host app's React
Entry point | `window.cloudinary.galleryWidget(config)` | `import { Gallery } from '@cloudinary/product-gallery'` and `import { resolveConfig } from '@cloudinary/product-gallery/server'`
Stylesheet | Injected automatically | Must be imported: `@cloudinary/product-gallery/index.css` (~19 KB minified)
Server-side rendering | Not applicable | Supported
API surface | Full API (`render`, `update`, `on`, item methods, and so on) | `Gallery` component only

The **script embed** is what the rest of this guide describes by default: same `cloudinary.galleryWidget(...)` call, same `render()` method, same configuration parameters. If you're already using the script embed, your existing code should work as is, but check [Migrating from v1](#migrating_from_v1) for the script URL, sizing, and custom styling changes.

If you're building a React or Next.js app, install the npm package instead:

```shell
npm install @cloudinary/product-gallery
```

> **NOTE**: The npm package is **ESM only**; `require()` isn't supported. Peer dependencies are `react` and `react-dom` (`^18.0.0` or `^19.0.0`), and Node `>= 18` is required. See the [Product Gallery reference](product_gallery_reference) for the full list of package entry points.

For details on using the npm package, including server-side rendering, see [Server-side rendering with React and Next.js](#server_side_rendering_with_react_and_next_js).

## Migrating from v1

v2 keeps the same configuration parameters, methods, and events as v1.3.4, so a page that only calls the API (`galleryWidget()`, `render()`, `update()`, and `on()`) needs just the new script URL. A page whose own CSS or JavaScript depends on the widget's internal markup needs one more step. v2 doesn't replace v1 automatically: v1 implementations, including ones that load `latest`, stay on v1 until you change the script URL.

To move a script embed from v1 to v2:

1. **Change the script URL.** Replace `product-gallery.cloudinary.com/.../all.js` (any v1 version, including `latest` and pinned versions such as `1.2.9`) with a pinned v2 URL. The old domain keeps serving v1, which receives security updates only. Always pin an exact v2 version rather than using `latest`, and retest after each upgrade, especially if you rely on CSS overrides. See [Include the JavaScript file](#1_include_the_javascript_file).

    ```html
    <script src="https://product-gallery-v2.cloudinary.com/2.0.3/all.js" type="text/javascript">
</script>    ```

2. **Remove the `image.js` preload, if you have one.** If the page also preloads v1's `image.js` file, remove that line. It no longer returns a 404, but it loads nothing.
3. **Check whether your own CSS or JavaScript targets the widget's internal markup.** Look for selectors or code that use `data-test="..."`, `.thumbnails-wrap`, `.assetWrapper`, or attributes such as `[mode="expanded"]`. If you find any, add `useLegacyV1Mode: true` to the gallery configuration:

    ```js
    cloudinary.galleryWidget({
      cloudName: 'demo',
      container: '#my-gallery',
      mediaAssets: [{ tag: 'shoes' }],
      useLegacyV1Mode: true,
    }).render();
    ```

    Cloudinary has deprecated `useLegacyV1Mode`, and it applies to the script embed only. When it's `true`, the widget renders v1's markup hooks on top of v2: v1 `data-test` names (regardless of the `testAttributes` value), v1 wrapper elements such as `gallery-spacer` and `thumbnails-wrap`, v1 attributes such as `mode`, `selected`, `shape`, and `direction`, and v1's CSS strength. See the [reference](product_gallery_reference#widget_parameters).
4. **Test your product page.** Check that the gallery is visible, and that thumbnails, arrows, zoom, and your custom styling work.
5. **Plan to move off `useLegacyV1Mode`.** Restyle with v2's documented options, and remove the flag before the next major version.

Also check the following:

* **Sizing**: The widget no longer sets pixel `width` and `height` on itself, and fills the width of its container. If your layout relied on the old behavior, move the size constraint onto the container. This applies even with `useLegacyV1Mode`. See [Sizing and responsiveness](#sizing_and_responsiveness), which also explains how it differs from responsive assets and viewport breakpoints.
* **Custom styling**: If you customized the widget's styling or CSS in v1, expect differences after upgrading. v1 class names were randomly hashed, so any CSS that targeted them won't match in v2. Replace it with configuration parameters where possible, or rewrite it against the new class names. See [Customizing with CSS](#customizing_with_css).
* **React and Next.js apps**: You can keep using the script embed, or switch to the [npm package](#choosing_a_distribution) for server-side rendering. The npm package exposes only the `Gallery` component, so if you call `render()`, `update()`, `on()`, or item methods, stay on the script embed. The npm package ignores `useLegacyV1Mode`.

These behaviors stay the same as in v2, even with `useLegacyV1Mode: true`:

* Disabled arrows use `aria-disabled` and stay keyboard-focusable, so page CSS that uses `button:disabled` or `[disabled]` no longer applies.
* Image URLs come from v2's responsive `srcset`, so they differ from v1's. CDN caches warm up again after the switch.
* v2 no longer generates v1's class names (`css-...`) or uses the zoom pop-up's v1 element order.
* The video player is v4, so page CSS written for v1's player (`.vjs-...`) may need updating.

For the full list of v2 changes, see the [changelog](product_gallery_changelog).


## Install and configure the Product Gallery widget

To add Cloudinary's Product Gallery widget to your site:

**Prerequisite:** [Make sure client-side asset lists are enabled](#prerequisite_make_sure_client_side_asset_lists_are_enabled).

1. [Include the JavaScript file](#1_include_the_javascript_file): `https://product-gallery-v2.cloudinary.com/<version>/all.js`.
2. [Add a containing element for the widget](#2_add_a_containing_element_for_the_widget).
3. [Initialize the Product Gallery widget](#3_initialize_the_product_gallery_widget) with the `cloudinary.galleryWidget(options)` method. 
4. [Render the Product Gallery widget](#4_render_the_product_gallery_widget) with the `render()` method.
5. [Optional. Update the Product Gallery widget](#5_optional_update_the_product_gallery_widget) with the `update(options)` method.

> **TIP**:
>
> :title=Tips for quick code implementation:

> * You can select assets from the Media Library and [generate Product Gallery code](#generating_product_gallery_code_for_media_library_assets) for those assets in an interactive UI. The UI also enables you to set a variety of customizations and preview the output as well as the code for those settings.  
>     ![Generate Product Gallery in the Asset toolbar](http://res.cloudinary.com/demo/image/upload/f_auto/q_auto/bo_1px_solid_gray/docs/DAM/ml_product_gallery_generator.png "thumb: w_300,dpr_2, width:300, with_url:false, with_code:false")

> * You can use the [Cloudinary CLI](cloudinary_cli#make) to generate basic skeleton code for a Product Gallery: 
> ```
cld make product_gallery
```

### Prerequisite: Make sure client side asset lists are enabled

The Product Gallery needs access to [client-side asset lists](list_assets#client_side_asset_lists). By default, this delivery type is restricted. 

To enable it in your Console Settings, navigate to **Settings > Security > Restricted media types** and make sure that the **Resource List** checkbox is clear.

### 1. Include the JavaScript file 

Include the JavaScript file for a specific version of the Product Gallery, from the `product-gallery-v2.cloudinary.com` domain:

```html<script src="https://product-gallery-v2.cloudinary.com/2.0.3/all.js" type="text/javascript">
</script>```

> **NOTE**: The version number used above is the latest tested version at the time of publishing this page. Test the latest available version of the Product Gallery and update the version number in your code accordingly.

To use a different version, replace the version number in the URL. See the [changelog](product_gallery_changelog) for the available versions.

You can use `latest` in place of the version number (`https://product-gallery-v2.cloudinary.com/latest/all.js`) to always load the newest release, but don't do this in production: a new release can change the widget's behavior or styling without any change on your side.

> **NOTE**: The Product Gallery script embed moved to the `product-gallery-v2.cloudinary.com` domain. The previous domain, `product-gallery.cloudinary.com`, continues to serve v1, which receives security updates only: use the new domain for all new implementations, and update existing ones when convenient.
> **INFO**: For business-critical apps, you're advised to specify the version of the Product Gallery JavaScript file and not use `latest`, particularly if your implementation includes customizations.

See the [Product Gallery changelog](product_gallery_changelog) for available versions and [register for notifications](product_gallery_changelog#register_for_notifications) to stay informed of new releases. Only update the version numbers in your code after testing new releases.
The script is a classic script that defines `window.cloudinary`, so call `render()` only after it has loaded. Load it with `defer` (or place it at the end of `<body>`) and run your initialization code after the `DOMContentLoaded` event, or from a script that's also deferred. If you load it with `async`, wait for the script's `load` event before calling `cloudinary.galleryWidget()`. Cloudinary doesn't currently publish SRI (integrity) hashes for the script. If you want to use the `integrity` attribute, generate the hash yourself from the version-pinned script, and add `crossorigin="anonymous"`. Regenerate the hash whenever you change versions, and don't use `integrity` with `latest`, as its contents change with each release.

### 2. Add a containing element for the widget 

Place the HTML element on the page where you want the Product Gallery to be rendered. Make sure that the element has a unique `id` attribute (if more than one element with the specified ID exists, the first element will be used as the container for the widget). The widget is responsive and will take up all the available width of the element: if necessary, use the `style` attribute of the element to constrain its width.

For example:

```html
<div id="my-gallery" style="max-width:80%">
</div>
```

### 3. Initialize the Product Gallery widget

The JavaScript method for initializing the widget is publicly available after including the Product Gallery's JavaScript file, which instantiates the `cloudinary` class and grants access to the `cloudinary.galleryWidget(options)` method. This method creates a Product Gallery instance in memory, where `options` is a map of the Product Gallery parameters to apply. 

The options must include the following 3 required parameters:

* Your Cloudinary product environment `cloudName` parameter.
* The `container` element on the page for the widget.
* The `mediaAsset` parameter with all media given as an array of assets. The individual assets in the array can be described either by an [Asset](product_gallery_reference#asset) object or by a PublicID string (as a shortcut for images only). 

For a complete list of parameters available for configuring the Product Gallery widget, see the [Parameter](product_gallery_reference#parameters) tables. 

For example, to initialize a new widget populated with all images that have the "clock" tag:

```js
const myGallery = cloudinary.galleryWidget({ 
  container: "#my-gallery", 
  cloudName: "demo", 
  mediaAssets: [{ tag: "clock" }]    // by default mediaType: "image"
});
```

You can additionally define a number of optional [configuration parameters](cloudinary_sdks#configuration_parameters). For example, if you're an [Advanced plan](https://cloudinary.com/pricing) user with a private CDN and a custom distribution, you can set `privateCdn` and `secure` parameters to true, and configure the `secureDistribution` parameter to match your setup and ensure the widget delivers your assets using the correct URLs: 

```js
const myGallery = cloudinary.galleryWidget({ 
  container: "#my-gallery", 
  cloudName: "demo", 
  secure: true,
  privateCdn: true,
  secureDistribution: 'example.distribution.com',
  mediaAssets: [{ tag: "clock" }]    // by default mediaType: "image"
});
```

See [below](#populating_the_widget_examples) for more examples on populating the Product Gallery widget with assets.

> **TIP**: Check out the [Product Gallery interactive demo](https://demo.cloudinary.com/product-gallery/?editor) and try out some of the options.

### 4. Render the Product Gallery widget

The `galleryWidget` method creates and initializes the widget but doesn't display it until the `render()` method of the returned instance is called. 

For example:

```js
myGallery.render();
```

### 5. Optional. Update the Product Gallery widget

Use the `update(options)` method if you want to update an already rendered widget, where `options` is a map of Product Gallery widget configuration [parameters](product_gallery_reference#parameters) to apply.

For example:

```js
myGallery.update({
  mediaAssets: [{ tag: "sack" }]
});
```

> **INFO**: When using the script embed, to avoid memory leaks and performance issues, make sure to use the [destroy](product_gallery_reference#destroy) method before removing the Product Gallery widget container element from your DOM. The npm `<Gallery>` component has no `destroy()` or `update()` method. See [Updating and removing the npm Gallery component](#updating_and_removing_the_npm_gallery_component).


## Product Gallery video tutorial

This tutorial walks you through the steps described above.

  This video is brought to you by Cloudinary's video player - embed your own!Use the controls to set the playback speed, navigate to chapters of interest and select subtitles in your preferred language.
{videoTranscript:publicId=training/m-tutorial-product-gallery}

### Tutorial contents This tutorial presents the following topics. Click a timestamp to jump to that part of the video.
### Provide access to client-side resource lists
{table:class=tutorial-bullets}|  | 
| --- | --- |
| | To ensure you can display your assets on the Product Gallery, you should enable access to **client-side resource lists** in the **Security** page of your Console Settings. By default, this delivery type is restricted.|

### Tag your assets
{table:class=tutorial-bullets}|  | 
| --- | --- |
| | Tagging your assets will make it easy to declare the files in your JavaScript, as well as help if you ever need to quickly add assets to the Gallery at a later date.|

### Build your Product Gallery
{table:class=tutorial-bullets}|  | 
| --- | --- |
| | At the top of your HTML, you need to include Cloudinary's JavaScript file for the Product Gallery. Doing so will provide all of the Gallery's functionality.|

### Add a containing element to your page
{table:class=tutorial-bullets}|  | 
| --- | --- |
| | Directly after the Cloudinary JavaScript file, you need to add a containing element for the Gallery. This indicates where you want the Gallery to be rendered on your page or post.|

### Initialize the Product Gallery
{table:class=tutorial-bullets}|  | 
| --- | --- |
| | After the <code>div tags, we can initialize our Product Gallery. This can be as simple as declaring your product environment cloud name and the tagged assets, or as complex as adding custom options for each aspect.|

### Add transformations to assets
{table:class=tutorial-bullets}|  | 
| --- | --- |
| |  One of the main reasons people use Cloudinary is because of our amazing asset transformations, and you can apply those on the fly into your Product Gallery. All you have to do is declare the transformations in the <code>mediaAssets parameter.|

### View default transformations
{table:class=tutorial-bullets}|  | 
| --- | --- |
| |  We do automatically apply some of our most generally useful transformations to the assets. So, don't worry about manually declaring any of the defaults. |

### Change the carousel styles
{table:class=tutorial-bullets}|  | 
| --- | --- |
| |  At default, we provide a carousel of all the assets as thumbnails. This allows your visitors to see a preview of each item in the Gallery, as well as a way to scroll or jump to a specific asset. However, you may want to change the thumbnails to be indicator shapes or remove the carousel altogether.|

### Adjust carousel properties
{table:class=tutorial-bullets}|  | 
| --- | --- |
| |  If you decide to further adjust how the carousel looks, you can do this by overriding the properties for each style.|

### Customize your video functionality
{table:class=tutorial-bullets}|  | 
| --- | --- |
| | Customization is definitely possible with the <code>videoProps parameter, such as allowing you to set whether videos play on load or if the visitor can manually pause and play the content.|

### Place the Product Gallery on your site's pages and posts
{table:class=tutorial-bullets}|  | 
| --- | --- |
| | At this point, you've likely got your Gallery code where you want it to be. So, all you have to do is embed it on your site.

### Allow JavaScript in WordPress
{table:class=tutorial-bullets}|  | 
| --- | --- |
| | Some content management systems like WordPress block JavaScript in pages and posts at default. If this happens to you, you may need to install and activate certain plugins, such as [Code Embed](https://wordpress.org/plugins/simple-embed-code/#description). |

After watching this overview video, continue reading the sections below to get details on customizing and enhancing your Product Gallery. 

## Displaying assets

The Product Gallery widget can display **images**, **videos**, **360 spin sets**, and **3D models**. Use the `mediaAssets` parameter to populate the widget with all media given as an array of asset objects. The individual objects in the array can be described either by an [Asset](product_gallery_reference#asset) object or by a PublicID string (as a shortcut for images only). 

All assets are displayed alphanumerically by their PublicID in ascending order. You can add the [sortProps](product_gallery_reference#sortprops) parameter if you want to change the way the assets are ordered (the older `sort` parameter is [deprecated](product_gallery_reference#widget_parameters)). For example, to sort in descending order: `sortProps: { source: "public_id", direction: "desc" }`.

> **NOTE**: The widget gets tag-based asset lists from the [client-side asset list](list_assets#client_side_asset_lists), which supports listing up to 1000 resources per tag. The widget doesn't paginate: it displays every asset in the list (for example, all 379 images of a 379-image tag). If a tag contains a large number of assets, narrow it down with more specific tags or list individual public IDs, as a very large gallery is slow to load.

If the asset list can't be retrieved, the widget has no assets to display. This happens when the **Resource List** media type is [restricted](#prerequisite_make_sure_client_side_asset_lists_are_enabled), or when the tag doesn't exist or has no assets of the requested type (the list request returns a 404 error). The script embed doesn't throw an error in this case: it logs a warning to the browser console and displays a "No media assets available for preview" message in place of the gallery. The npm package behaves the same way: `resolveConfig` doesn't reject when a tag's list fails or is empty. It logs a console warning, leaves that tag's assets out of `mediaAssets`, and resolves, and `<Gallery>` displays the same message if no assets remain. No [event](#gallery_events) fires in either case. Check the browser's network tab for the failed list request to diagnose an empty gallery.

For example, to populate the widget with all images that have the "shoe" tag:

```js
const myGallery = cloudinary.galleryWidget({ 
  container: "#my-gallery", 
  cloudName: "demo", 
  mediaAssets: [{ tag: "shoe" }]   // by default mediaType: "image"
});
```

> **NOTES**:
>
> * The Product Gallery widget only displays media assets that were uploaded as delivery [type](control_access_to_media) `upload`.

> * The Product Gallery widget is incompatible with the [Strict Transformations](control_access_to_media#strict_transformations) feature due to the number of transformations that need to be generated on the fly.

> **In this section**:
>
> * [Videos](#videos)

> * [360 spin sets](#360_spin_sets)

> * [3D models](#3d_models)

> * [Display mode](#display_mode)

> * [Responsive assets](#responsive_assets)

> * [Applying transformations](#applying_transformations)

> * [Populating the widget examples](#populating_the_widget_examples)

### Videos

To play videos in the Product Gallery widget, populate the `mediaAssets` parameter with an [Asset](product_gallery_reference#asset) object: specify the `tag` used for all videos with the same tag or specify the `public_id` of the video asset, and specify the `mediaType` property with a value of "video".

For example, to populate the widget with all videos that have the "shirt" tag:

```js
const myGallery = cloudinary.galleryWidget({ 
  container: "#my-gallery", 
  cloudName: "demo", 
  mediaAssets: [{ tag: "shirt", mediaType: "video" }]   
});
```

> **NOTE**: The Product Gallery widget plays videos using the HTML5 video player by default, but you can use the [Cloudinary Video Player](#cloudinary_video_player) instead.

### 360 spin sets

 360 spin sets allow your users to spin a product around a central axis. In order to display a 360 spin set, the Product Gallery widget fetches all images with a particular tag and combines them into a single entity, where each image is included as a single frame of the resulting 360 spin set (sorted alphanumerically by their public ID). 

To add a 360 spin set, populate the `mediaAssets` parameter with an [Asset](product_gallery_reference#asset) object: specify the `tag` used for all images in the 360 spin set, and specify the `mediaType` with a value of "spin".

For example, to populate the widget with a single 360 spin set created from all images in the `demo` product environment that have the `clock-360` tag:

```js
const myGallery = cloudinary.galleryWidget({ 
  container: "#my-gallery", 
  cloudName: "demo", 
  mediaAssets: [{ tag: "clock-360", mediaType: "spin" }] 
});
```

#### Spin sets from Panoramic 360 images

An interesting use case for spin sets is to display 360 panoramic images that can also be rotated by a user, giving the effect to the user of turning in place while seeing the 360 view. The Product Gallery below displays a 360 spin set and the original landscape image it was created from. For more details, as well as a simple script for making a spin set from a panoramic image, see the blog post on [How to Turn 360 Panoramic Images Into 360 Spin Sets](https://cloudinary.com/blog/how-to-turn-360-panoramic-images-into-360-spin-sets).

### 3D models

3D models are one of the best ways for your users to interact with a product and view it online from multiple angles. The Product Gallery widget supports 3D models that have been zipped and uploaded to Cloudinary (see [Uploading 3D models](upload_parameters#uploading_3d_models) for more information). 

To add a 3D model, populate the `mediaAssets` parameter with an [Asset](product_gallery_reference#asset) object: specify the `publicId` of a single model (or a `tag` for multiple models) and specify the `mediaType` with a value of "3d". 

You can also control how the model is displayed and the look and feel of the zoom and augmented reality (AR) controls by including the [ar3dProps](product_gallery_reference#ar3dprops) parameter.

For example, to populate the widget with a 3D model in the `demo` product environment that has the public ID of `DamagedHelmet3D`, and set it to rotate automatically:

```js<script src="https://product-gallery-v2.cloudinary.com/2.0.3/all.js" type="text/javascript">
</script>
<div id="my-gallery2"></div>

<script type="text/javascript">  
const myGallery2= cloudinary.galleryWidget({
  container: "#my-gallery2",
  cloudName: "demo",
  mediaAssets: [
    {publicId: "DamagedHelmet3D", mediaType: "3d"}
  ],
  ar3dProps: {
    showAR: true,
    autoRotate: true
  }
});

myGallery2.render();
</script>
```

> **NOTE**: The Product Gallery only supports 3D models in the GLB format. If an uploaded 3D model is in a different format (e.g., FBX) Cloudinary will try convert it to GLB. This conversion process is still in development and may result in errors. We recommend converting to the GLB format before uploading the model to Cloudinary.

#### Customizing AR functionality

You can customize the AR (augmented reality) experience by using your own custom AR modal and/or button instead of the default ones provided by the Product Gallery widget.

##### Using a custom AR modal

To use a custom AR modal while keeping the native "view in AR" button, set `useCustomArModal: true` and listen to the `onArClick` event to display your custom modal when the button is clicked:

```js
const myWidget = cloudinary.galleryWidget({
  cloudName: 'demo',
  container: '#my-gallery',
  carouselStyle: 'none',
  ar3dProps: {
    showAR: true,
    useCustomArModal: true,
  },
  mediaAssets: [
    { publicId: "docs/3d/red_sneaker", mediaType: "3d" },
  ]
});

myWidget.on('onArClick', (e) => {
  const { qrUrl, qrSvg } = e.data;
  const modal = document.getElementById('ar-modal');
  const qrContainer = document.getElementById('ar-qr-code');
  const urlContainer = document.getElementById('ar-url');

  qrContainer.innerHTML = qrSvg;
  urlContainer.innerHTML = `<a href="${qrUrl}" target="_blank">${qrUrl}</a>`;
  modal.style.display = 'flex';

  document.getElementById('close-modal').onclick = () => {
    modal.style.display = 'none';
  };
});

myWidget.render();
```

HTML template:

```html
<div class="gallery-container" style="position: relative;">
 <div id="my-gallery"></div>
 <div id="ar-modal" class="modal-overlay" style="display: none;">
   <div class="modal-content">
     <h2>AR Instructions</h2>
     <p>Scan this QR code with your mobile device to view in AR</p>
     <div id="ar-qr-code"></div>
     <div id="ar-url" class="ar-url"></div>
     <button id="close-modal">Close</button>
   </div>
 </div>
</div>
```

 
 
   
     AR Instructions
     Scan this QR code with your mobile device to view in AR
     
     
     Close
   
 

##### Using a custom AR button

To use a custom "view in AR" button and a custom AR modal to display the QR code, set `showAR: false` to hide the native AR button and listen to the `onQrReady` event to capture the QR code data when it's ready:

```js
window.addEventListener('load', () => {

 const myWidget = cloudinary.galleryWidget({
   cloudName: 'demo',
   container: '#my-gallery',
   carouselStyle: 'none',
   ar3dProps: {
     showAR: false, // Hides the native "view in AR" button
   },
   mediaAssets: [
     { publicId: "docs/3d/red_sneaker", mediaType: "3d" },
   ]
 });

 myWidget.on('onQrReady', (e) => {
   const { qrSvg, qrUrl } = e.data;
   const customArButton = document.getElementById('custom-ar-button');
   customArButton.onclick = () => {
     const modal = document.getElementById('ar-modal');
     const qrContainer = document.getElementById('ar-qr-code');
     const urlContainer = document.getElementById('ar-url');

     qrContainer.innerHTML = qrSvg;
     urlContainer.innerHTML = `<a href="${qrUrl}" target="_blank">${qrUrl}</a>`;
     modal.style.display = 'flex';

     document.getElementById('close-modal').onclick = () => {
       modal.style.display = 'none';
     };
   };
 });

 myWidget.render();
});
```

HTML template:

```html
<div class="gallery-container" style="position: relative;">
 <div id="my-gallery"></div>
 <button id="custom-ar-button">View in AR</button>
 <div id="ar-modal" class="modal-overlay" style="display: none;">
   <div class="modal-content">
     <h2>AR Instructions</h2>
     <p>Scan this QR code with your mobile device to view in AR</p>
     <div id="ar-qr-code"></div>
     <div id="ar-url" class="ar-url"></div>
     <button id="close-modal">Close</button>
   </div>
 </div>
</div>
```

 
 View in AR
 
   
     AR Instructions
     Scan this QR code with your mobile device to view in AR
     
     
     Close
   
 

### Display mode

The following video gives a brief demonstration of the different display modes for the Product Gallery:

The Cloudinary Product Gallery widget can be configured with the following parameters of the `displayProps` object:

* `mode`:
    * **classic** - (Default) The assets are displayed one at a time in the main viewer. 
    * **expanded** - The main viewer is expanded and all assets are displayed in vertical columns. Not supported by mobile devices where the widget always uses classic mode.

    The following parameters of the`displayProps` object are relevant only when the `mode` parameter is set to 'expanded':

* `spacing` - The spacing between assets in pixels.
* `columns`- The number of columns to display simultaneously (1 column by default). 
* `topOffset` - The offset of the carousel and the selected asset from the top of the page in pixels (to account for other elements on the page, like menus). 
* `bottomOffset` - The offset of the carousel and the selected asset from the bottom of the page in pixels (to account for other elements on the page, like footers). 

For example, to configure the widget to display all assets in an expanded viewer:

```js 
var myGallery= cloudinary.galleryWidget({
  container: "#my-gallery",
  cloudName: "demo",
  displayProps: {
    mode: "expanded",
    topOffset: 70 // to account for the menu element at the top of this documentation page
  },
  aspectRatio: "4:3", // most of the assets are in landscape orientation
  mediaAssets: [
    {tag: "electric_car_product_gallery_demo"}, // by default mediaType: "image"
    {tag: "electric_car_product_gallery_demo", mediaType: "video"}, 
    {tag: "electric_car_360_product_gallery_demo", mediaType: "spin"}
  ]
});
myGallery.render();
```

> **NOTES**:
>
> When the widget is configured for `expanded` mode:

> * The [carousel](#carousel_options) is rendered as a floating element (by default). This property is controlled by the `sticky` parameter of the carousel customization object ([ThumbnailProps](product_gallery_reference#thumbnailprops) or [IndicatorProps](product_gallery_reference#indicatorprops)). 

> * The height of your displayed assets shouldn't be larger than the viewport height, which can potentially be an issue on large screen resolutions. Note that the height is controlled indirectly by a combination of the container width + aspect ratio. Best practice is to either set a fixed width for your container, and/or select an appropriate aspectRatio (e.g., 4:3 for landscape).

> * Not all browsers support 'scrollTo' behavior by default. To smoothly scroll to selected assets, instead of 'jumping' to them instantly on Edge and Safari browsers, include a [polyfill for scrollTo behavior](https://github.com/iamdustan/smoothscroll).

### Responsive assets

The Cloudinary Product Gallery widget delivers responsive, appropriately sized media assets using native `srcset` and `sizes` attributes: the browser picks the best-fitting asset for the space it actually occupies, from a ladder of Cloudinary dynamic transformation URLs scaled to breakpoint steps (every 100 pixels by default) according to resolution.

> **NOTE**: In v1.3 and earlier, the widget measured the container in JavaScript and requested a single scaled asset accordingly, using client-side scaling if the window was scaled down. If you're on v1, see the [changelog](product_gallery_changelog) for the exact version where this changed.

This section covers how individual media assets are delivered responsively. For sizing the widget's container itself, see [Sizing and responsiveness](#sizing_and_responsiveness).

To change the breakpoint step size, you can include the following optional parameters:

* `imageBreakpoint` to override the value for images and 360 spin sets assets (default: 100).
* `videoBreakpoint` to override the value for video assets (default: 100). 

For example, to change the breakpoint step size to every 150 pixels for the images, and to 200 pixels for the videos:

```js
var myGallery = cloudinary.galleryWidget({ 
  container: "#my-gallery", 
  cloudName: "demo", 
  mediaAssets: [
    { tag: "bag" }, 
    { tag: "bag", mediaType: "video" }
  ],
  imageBreakpoint: 150,
  videoBreakpoint: 200 
});
myGallery.render();
```

### Applying transformations

By default, the widget applies the following [transformations](transformation_reference) to media assets displayed in the widget: 

* **For images** (including 360 spin sets):

    ```json
    {
      background: "#FFFFFF", // only relevant for pad crop mode
      crop: "pad",           // only fill or pad mode is supported
      dpr:  2,          
      fetch_format: "auto", 
      quality: "auto",
      gravity: "auto"        // only relevant for fill crop mode (default is "center" for 360 spin sets)
    }
    ```

* **For videos**:

    ```json
    {
      background: "#FFFFFF", // only relevant for pad crop mode
      crop: "pad",           // only fill or pad mode is supported
      dpr:  2,          
      duration: 30
    }
    ```

You can override any of these default transformations by adding the `transformation` parameter to the [Asset](product_gallery_reference#asset) object when populating the widget with the `mediaAssets` parameter. 

For example, to use the `fill` crop mode instead of the default `pad` crop mode:

```js
mediaAssets: [{ tag: "shirt", transformation: { crop: "fill" } }]
```

If you also want to add other transformation parameters, use the `transformation` *object* of the `transformation` *parameter*. For example, to add images tagged with "shirt" and also add an overlay of the `cloudinary_icon_blue` image in the top right corner: 

```js
mediaAssets: [{ tag: "shirt", transformation: 
  { transformation: [{ overlay: "cloudinary_icon_blue", gravity: "north_east" }]}}]
```

You can both override transformation parameters and supply additional parameters. For example, to add images tagged with "shirt" that now use the `fill` crop mode, and also add an overlay of the `cloudinary_icon_blue` image in the top right corner: 

```js
mediaAssets: [{ tag: "shirt", transformation: 
  { crop: "fill", transformation: [{ overlay: "cloudinary_icon_blue", gravity: "north_east" }]}}]
```

By default, the default transformations are applied before the additional transformations. If you want to apply the default transformations after the additional ones, set the `prefixed` parameter to `false`. For example, to remove the background of the images before applying the default transformations:

```js
mediaAssets: [{ tag: "shirt", transformation: 
{ prefixed: false, effect: "background_removal" }}]
```
> **NOTE**: All transformations use the JavaScript (legacy) syntax. When looking at transformation examples in the rest of the documentation, you can change the JS tab to display the legacy (cloudinary-core) code examples.
### Populating the widget examples

The `mediaAssets` parameter is used to populate the widget. The parameter accepts an array of values where each of them can be described either by an [Asset](product_gallery_reference#asset) object or by a PublicID string (as a shortcut for a single image only).

The following are example values for the `mediaAssets` parameter:

1. All images tagged with "shirt":
   
    ```js
   [{tag: "shirt"}]   // by default mediaType: "image"
    ```
2. All video assets tagged with "bag":
   
    ```js
    [{tag: "bag", mediaType: "video"}]  
    ```
3. All images tagged with "bag" and all videos tagged with "luggage":
    
    ```js
    [{tag: "bag", mediaType: "image"}, {tag: "luggage", mediaType: "video"}]
    ```
4. A video asset with the PublicID "t-shirt":
    
    ```js
    [{publicId: "t-shirt", mediaType: "video"}]
    ```
5. A 360 spin set created from all static images tagged with "my-360-tag":
   
    ```js
    [{tag: "my-360-tag", mediaType: "spin"}]
    ```
6. An image with the PublicID "bag" with a cartoonify effect applied:
   
    ```js
    [{publicId: "bag", transformation: {effect: "cartoonify"}}]
    ```
7. An image created from the middle frame of a video asset with the PublicID "clock":
    
    ```js
    [{publicId: "clock", mediaType: "image", resourceType: "video"}]
    ```
8. An image with the PublicID "book", a 360 spin set created from all static images tagged with "360-book", and a video with the PublicID "book-vid":
   
    ```js
   ["book", {tag: "360-book", mediaType: "spin"}, {publicId: "book-vid", mediaType: "video"}]
    ```  

## Sizing and responsiveness

"Responsive" covers three separate things in the Product Gallery widget, each with its own section:

Section | What it controls | Configured with | Responds to
---|---|---|---
[Responsive assets](#responsive_assets) | Which image or video file the browser downloads | `imageBreakpoint`, `videoBreakpoint` | The space the asset occupies
Sizing and responsiveness (this section) | The width of the whole widget | CSS on your container, and `aspectRatio` | The container's width
[Responsive widget](#responsive_widget) | The widget's layout (carousel position and style, navigation) | `viewportBreakpoints` | The viewport width

The widget fills the width of its parent element and derives its height from the [aspectRatio](product_gallery_reference#aspectratio) parameter using native CSS. This means:

* **To size the gallery, style its container**, not the widget. Use `max-width`, a grid or flex cell, or any other CSS technique to constrain the container's width.
* There are no `width` or `height` configuration parameters for the widget.
* The container must have a resolvable width. A parent with no width (for example, an unconstrained inline-level or zero-width element) leaves nothing for the widget to fill.
* Everything is fluid by default: resizing the viewport adjusts the widget's layout without a JavaScript re-layout.

> **NOTE**: In v1.3 and earlier, the widget measured its container in JavaScript and set pixel `width`/`height` on itself, so a layout that relied on this may need the equivalent constraint moved onto the container. If you're on v1, see the [changelog](product_gallery_changelog) for the exact version where this changed.
For example:

```html
<!-- constrain the container; the widget fills it and derives height from aspectRatio -->
<div style="max-width: 800px; width: 100%; margin: 0 auto;">
  <!-- gallery here -->
</div>

<!-- works the same inside a grid or flex cell -->
<div style="display: grid; grid-template-columns: 2fr 1fr; gap: 24px;">
  <div><!-- gallery fills this column --></div>
  <aside>Product details</aside>
</div>
```

```html
<!-- doesn't work: no width to fill, so the widget has nothing to size against -->
<span><!-- gallery here --></span>
```

> **NOTE**: If you're rendering the widget on a server (see [Server-side rendering with React and Next.js](#server_side_rendering_with_react_and_next_js)), there's no browser available to measure the container. Set the [viewerWidthHint](product_gallery_reference#widget_parameters) parameter to match the container's width so the widget can select an appropriately sized image and avoid a hydration mismatch.

## Server-side rendering with React and Next.js

> **NOTE**: Server-side rendering requires the [npm package](#choosing_a_distribution) distribution. It isn't available with the script embed.

The npm package supports rendering the gallery on the server and hydrating it on the client. Two integration shapes are covered below: Next.js App Router, and generic React SSR for other pipelines (Express, Remix, and so on).

> **In this section**:
>
> * [Next.js App Router](#next_js_app_router)

> * [Generic React server-side rendering](#generic_react_server_side_rendering)

> * [Server-side rendering considerations](#server_side_rendering_considerations)

### Next.js App Router

To render the gallery with SSR in a Next.js App Router project (for a complete working app, see the [Next.js sample app on GitHub](https://github.com/cloudinary-devs/cloudinary-product-gallery-nextjs)):

1. Import the widget's stylesheet once, in the root layout:

    ```tsx
    // app/layout.tsx - import the stylesheet once
    import '@cloudinary/product-gallery/index.css';

    export default function RootLayout({ children }: { children: React.ReactNode }) {
      return (
        <html lang="en">
          <body>{children}</body>
        </html>
      );
    }
    ```

2. In a **Server Component**, call `resolveConfig(userConfig)` from `@cloudinary/product-gallery/server` and pass the result to a Client Component. `resolveConfig` merges defaults, initializes Cloudinary, and resolves `mediaAssets` (including tag-based and resource-list queries, which is why it's `async`).

    Since there's no browser on the server to measure the container, also set the [viewerWidthHint](product_gallery_reference#widget_parameters) parameter to tell the widget how wide its container will be, using the same number as the container's `max-width`:

    ```tsx
    // app/page.tsx - Server Component: resolve the config on the server
    import { resolveConfig } from '@cloudinary/product-gallery/server';
    import { GalleryClient } from './GalleryClient';

    const MAX_WIDTH = 800; // the widget container's width on screen

    export default async function Page() {
      const resolvedConfig = await resolveConfig({
        cloudName: 'demo',
        mediaAssets: [{ publicId: 'dog' }, { publicId: 'cat' }],
        aspectRatio: '4:3',
        viewerWidthHint: MAX_WIDTH, // same number as the container's max-width
      });

      return (
        <div style={{ maxWidth: MAX_WIDTH, width: '100%', margin: '0 auto' }}>
          <GalleryClient resolvedConfig={resolvedConfig} />
        </div>
      );
    }
    ```

3. In a **Client Component**, render `<Gallery resolvedConfig={...} />` with the config passed down from the Server Component:

    ```tsx
    // app/GalleryClient.tsx - Client Component: render the gallery
    'use client';

    import { Gallery, type ConfigProps } from '@cloudinary/product-gallery';

    export function GalleryClient({ resolvedConfig }: { resolvedConfig: ConfigProps }) {
      return <Gallery resolvedConfig={resolvedConfig} />;
    }
    ```

### Generic React server-side rendering

For other server pipelines (Express, Remix, and custom setups), use `renderToString(<Gallery resolvedConfig={...} />)` on the server and `hydrateRoot` on the client, with the resolved config serialized into the page so both sides use identical input.

1. On the server, call `resolveConfig` and render the gallery to an HTML string with `renderToString`, then send that HTML to the browser with the resolved config embedded as JSON, so the client can reuse the exact same values when hydrating. Also serve `node_modules/@cloudinary/product-gallery/dist/index.css` as `/gallery.css`, or inline it as described in [Server-side rendering considerations](#server_side_rendering_considerations) below:

    ```jsx
    // server.mjs
    import express from 'express';
    import { createElement } from 'react';
    import { renderToString } from 'react-dom/server';
    import { resolveConfig } from '@cloudinary/product-gallery/server';
    import { Gallery } from '@cloudinary/product-gallery';

    const app = express();

    app.get('/', async (_req, res) => {
      const resolvedConfig = await resolveConfig({
        cloudName: 'demo',
        mediaAssets: [{ publicId: 'dog' }, { publicId: 'cat' }],
        aspectRatio: '4:3',
        viewerWidthHint: 800,
      });

      const html = renderToString(createElement(Gallery, { resolvedConfig }));

      res.send(`<!doctype html>
    <html lang="en">
      <head>
        <link rel="stylesheet" href="/gallery.css" />
      </head>
      <body>
        <div id="gallery" style="max-width:800px;width:100%;margin:0 auto">${html}</div>
        <script type="application/json" id="gallery-config">${JSON.stringify(resolvedConfig)}</script>
        <script type="module" src="/client.js"></script>
      </body>
    </html>`);
    });

    app.listen(3000);
    ```

2. On the client, read the embedded config back out and hydrate with `hydrateRoot`, using the same config the server used:

    ```jsx
    // client.js - hydrate with exactly the same config the server used
    import { createElement } from 'react';
    import { hydrateRoot } from 'react-dom/client';
    import { Gallery } from '@cloudinary/product-gallery';

    const resolvedConfig = JSON.parse(document.getElementById('gallery-config').textContent);

    hydrateRoot(
      document.getElementById('gallery'),
      createElement(Gallery, { resolvedConfig }),
    );
    ```

### Server-side rendering considerations

* **Stylesheet delivery.** `import '@cloudinary/product-gallery/index.css'` assumes a CSS-aware bundler (Next.js, Vite, webpack). Without one, import the stylesheet as a string and inline it into the document `<head>`:

    ```tsx
    import galleryStyles from '@cloudinary/product-gallery/index.css';

    // somewhere in your document <head>:
    <style dangerouslySetInnerHTML={{ __html: galleryStyles }} />
    ```

* **`undefined` values don't survive serialization.** Any config key whose value is `undefined` is dropped when the resolved config is serialized to the client. This is harmless: `<Gallery>` re-merges the full default set internally, but it explains why a logged `resolvedConfig` can look different on each side.
* **`viewportBreakpoints` apply after hydration.** The server renders the base configuration with no breakpoint overrides, so the initial markup matches the server exactly. Breakpoint overrides then apply as a normal client-side update, so on a small viewport the breakpoint layout appears a moment after first paint. This is by design and keeps hydration clean.
* **Set `viewerWidthHint`**, or accept `sizes="100vw"` and a potentially oversized first image request.

> **NOTE**: The React (npm) build's `Gallery` component doesn't currently expose the [event API](#gallery_events), the imperative [instance methods](product_gallery_reference#instance_methods) (`on`, `setItem`, `nextItem`, and so on), or the `container` parameter (React places the component itself). If you need these, use the [standalone script embed](#choosing_a_distribution) instead.

## Using the npm package in a client-only React app

The npm package also works in a client-rendered single-page app (for example, one built with Vite), with no server involved. This is a supported setup: call `resolveConfig` in the browser, then render `<Gallery>` with the result. Import the stylesheet in this setup too, as the widget doesn't inject its own styles when you use the npm package.

```tsx
// src/ProductGallery.tsx
import { useEffect, useState } from 'react';
import { Gallery, type ConfigProps } from '@cloudinary/product-gallery';
import { resolveConfig } from '@cloudinary/product-gallery/server';
import '@cloudinary/product-gallery/index.css'; // required

export function ProductGallery({ tag }: { tag: string }) {
  const [resolvedConfig, setResolvedConfig] = useState<ConfigProps | null>(null);
  const [error, setError] = useState(false);

  useEffect(() => {
    let cancelled = false;
    // clear the previous tag's config so it isn't shown while the new one resolves
    setResolvedConfig(null);
    setError(false);
    resolveConfig({
      cloudName: 'demo',
      mediaAssets: [{ tag }],
    })
      .then((config) => {
        if (!cancelled) setResolvedConfig(config);
      })
      .catch(() => {
        if (!cancelled) setError(true);
      });
    return () => {
      cancelled = true;
    };
  }, [tag]);

  if (error) return <p>The gallery couldn't be loaded.</p>;
  if (!resolvedConfig) return null;

  // key remounts the gallery when the tag changes
  return <Gallery key={tag} resolvedConfig={resolvedConfig} />;
}
```

### Updating and removing the npm Gallery component

The npm `<Gallery>` component exposes no `update()` or `destroy()` method. Those methods belong to the [script embed](#5_optional_update_the_product_gallery_widget). To change what the gallery shows (for example, when a `tag` prop changes), call `resolveConfig` again and render `<Gallery>` with the new `resolvedConfig`, giving it a `key` that changes with the config so React remounts it, as in the example above. Clear the previous config while the new one resolves, so the old assets aren't shown in the meantime. You don't call `destroy()` before removing the component: remove it like any other React component. When you remove it, React removes the gallery's DOM, and the component removes the listeners it added to `window` and `document`.

### Bundle size and code splitting

The npm package statically imports three.js, which it uses to display 3D models, so your main bundle includes it even if your gallery displays only images. In a Vite build, this results in a large main chunk (around 1.26 MB at the time of writing) and Vite's chunk size warning. The Video Player and its dash and video.js dependencies aren't in the main chunk: Vite splits them into separate chunks that load only when the gallery needs them. To keep this out of your main bundle, load the gallery component lazily, so that the chunk loads only on pages that show a gallery:

```tsx
import { lazy, Suspense } from 'react';

const ProductGallery = lazy(() =>
  import('./ProductGallery').then((m) => ({ default: m.ProductGallery })),
);

export function Product() {
  return (
    <Suspense fallback={null}>
      <ProductGallery tag="bag" />
    </Suspense>
  );
}
```

## Customizing styles

The Product Gallery interface is extensively customizable, whether you need to increase the size of thumbnails in the carousel, move the location of the zoom viewer or implement your own colorization scheme. See the [Product Gallery reference](product_gallery_reference) documentation for a listing of all the customization options. If you need to go beyond the configuration parameters, see [Customizing with CSS](#customizing_with_css) below.

> **TIP**: Check out the [Product Gallery interactive demo](https://demo.cloudinary.com/product-gallery/?editor) and try out some of the customization options.

### Customizing with CSS

> **NOTE**: CSS customization is available in v2, in both the npm package and the standalone build. It isn't available in v1.

The widget renders plain CSS with stable, human-readable class names and CSS custom properties, so anything the configuration parameters don't cover can be adjusted from a stylesheet. (In v1, styles were generated at runtime with randomly hashed class names, so customer CSS couldn't reliably target anything and configuration parameters were the only lever.)

There's no published exhaustive list of class names and custom properties. Instead:

* Everything the widget renders is scoped under a `.pgw` root class, with human-readable class names (`thumbnailItem`, `navButton`, `indicatorWrap`, `popupOverlay`, and so on) and `--modifier` suffixes for state and variants (`thumbnailItem--selected`, `navButton--left`).
* Colors, sizes, borders, radii, and gaps are driven by CSS custom properties (`--gw-*`, `--thumb-*`, `--ind-*`, and so on).
* **Inspect the widget in your browser's devtools** to find the class or variable you want to target: that's the intended discovery path, and the reason the names are readable.
* Prefer a configuration parameter when one exists; CSS is the escape hatch for what the configuration doesn't reach.

> **NOTE**: Class names and custom properties may change between releases. If you rely on CSS overrides, pin an exact widget version rather than tracking `latest`, and re-check your overrides when you upgrade.

#### Overriding widget styles

Values derived from your configuration are written as inline styles on the widget's root element. Since an inline declaration beats any stylesheet rule, overriding one of those specific values from CSS requires `!important`. Everything else overrides normally:

```css
/* 1. A plain CSS property on a class - equal specificity is enough.
      Widget rules are emitted as `.pgw .someClass`, so a bare
      `.someClass { }` won't win - always include `.pgw`. */
.pgw .thumbnailItem {
  border-radius: 12px;
}

/* 2. A custom property on a descendant element - no !important needed */
.pgw .thumbnailItem--selected {
  --thumb-sel-border: 3px solid #e91e63;
}

/* 3. Icon colors live on the SVG inside the button */
.pgw .navButton path {
  fill: #0a141e;
}

/* 4. A config-derived custom property on the root - !important IS required,
      because the widget writes these as inline styles on that element */
.pgw.galleryWrapper {
  --gw-loader-color: #010203 !important;
}
```

The following two patterns look correct but don't work, since both are overridden by the widget's own inline style on the root element:

```css
/* setting a widget variable on an ancestor: loses to the root's inline value */
#my-gallery { --gw-nav-btn-color: red; }

/* setting it on the root without !important: same problem */
.pgw.galleryWrapper { --gw-nav-btn-color: red; }
```

## Carousel options

The carousel is the component of the widget that's used for indicating the amount of assets, showing which asset is currently displayed in the main viewer, and for cycling through the assets. There are 2 styles defined for the carousel, which can be set with the [carouselStyle](product_gallery_reference#carouselstyle) parameter:

* `thumbnails` -  small thumbnail images. 
    
* `indicators` -  a series of small icons. 
* `none` - no carousel component is displayed: only the main viewer navigation buttons are available for cycling through the assets.

Both styles are highly customizable and the default values can be changed by overriding the `thumbnailProps` parameter with a new [ThumbnailProps](product_gallery_reference#thumbnailprops) object or overriding the `indicatorProps` parameter with a new [IndicatorProps](product_gallery_reference#indicatorprops) object.

For example, to customize the thumbnail style to display 75x75 images, set a spacing of 4 pixels between the images, and color the navigation buttons green:

```js
var myGallery = cloudinary.galleryWidget({ 
  container: "#my-gallery", 
  cloudName: "demo", 
  carouselStyle: "thumbnails",   // default value: included for clarity
  thumbnailProps: { width: 75, height: 75, spacing: 4, navigationColor: "green"},
  mediaAssets: [{ tag: "bag" }] });
myGallery.render();
```

## Generating Product Gallery code for Media Library assets

You can select images, videos, and 360 spin sets from your Media Library and automatically generate the code for a Product Gallery containing these assets. When you use this option, the Product Gallery generator UI opens, displaying a preview of the Product Gallery with default style and carousel options. You can then use the Generator UI options to customize the Gallery styles and carousel options. As you make your selections, both the preview and gallery code update automatically.

![Generate Product Gallery in the Asset toolbar](http://res.cloudinary.com/demo/image/upload/f_auto/q_auto/bo_1px_solid_gray/docs/DAM/ml_product_gallery_generator.png "thumb: w_425,dpr_2, width:425, with_url:false, with_code:false")

Besides enabling you to quickly generate your Product Gallery code and experiment with the various customization options, this can also be a useful tool for working together with product or marketing managers to decide on the preferred customizations before implementation.

> **NOTE**: The Product Gallery is accessible from the Media Library only if your Assets administrator has enabled the Product Gallery in the [Apps](dam_apps_options) marketplace.

**To generate Product Gallery code from the Media Library**: 

1. In your application code, include the Product Gallery JavaScript file and a containing element for the widget, as described in the first steps of the Product Gallery [installation workflow](#install_and_configure_the_product_gallery_widget). Additionally, verify the following options are set in your [Console Settings](https://console.cloudinary.com/console):
   * Make sure the **Resource List** checkbox is cleared in **Settings > Security > Restricted media types**.  
   * If your product environment is set to use [Strict Transformations](control_access_to_media#strict_transformations), add your domain to the list in **Settings > Security > Allowed strict referral domains**.
2. In the Media Library, select the assets you want to include in your gallery.  
   * If all the required assets aren't stored in the same folder, you may first want to add them all to the same [Media Library collection](dam_folders_collections_sharing) or perform an [advanced search](dam_advanced_search) (based on a tag value or other value that they have in common), so that all the required assets are in the same view for easy selection. 
   * The assets you select must be of type `upload` (not fetched or social media assets) and must be public (not restricted).
   * By default, the assets you select will be added to the gallery in ascending alphabetical order by public ID. If you want to control the order of the assets, you must do some reparation. For details, see [Controlling the order of assets in a generated Product Gallery](#controlling_the_order_of_assets_in_a_generated_product_gallery)
   * If you want to include 360 spin sets in your Product Gallery, you must do some preparation. For details, see [Including 360 spin sets in a generated Product Gallery](#including_360_spin_sets_in_a_generated_product_gallery).
   * Currently, adding 3D models to a generated Product Gallery via the UI isn't supported. You can [add 3D models](#3d_models) to your code manually after you copy the embed code to your container element in your application or site code.
3. In the asset toolbar, select **Generate Product Gallery**. 
    
    ![Generate Product Gallery in the Asset toolbar](https://cloudinary-res.cloudinary.com/image/upload/q_auto/f_auto/bo_1px_solid_gray/v1649768518/docs/ml_gen_prod_gallery_option.png "thumb: w_510,dpr_2, width:510, with_code:false, with_url:false")

    The Product Gallery Generator opens and displays the preview and embed code for the Product Gallery with your selected assets.
    
4. After customizing the Product Gallery options to fit your needs, use the **Copy to Clipboard** button to capture the embed code for your Product Gallery and paste it within a `script` HTML tag in your application code.The generated code assumes that your container ID is: `"#my-gallery"`.  Adjust this as needed.

### Controlling the order of assets in a generated Product Gallery
When assets are added to a Product Gallery by public ID, the order that the assets are displayed is based on the order that they're specified within the `mediaAssets` object. By default, when you select assets from the Media Library for inclusion in the Product Gallery generator, they're added to the `mediaAssets` object in ascending alphabetical order by public ID. To instruct the Product Gallery generator to add the assets to the `mediaAssets` object in another order, add a **contextual metadata** key called `placement` to each asset. The value of this key for each asset should be a numerical value, where `1` represents the first asset displayed in the gallery.

> **TIP**:
>
> :title=Tips:

> * You can sort the assets displayed in the Assets, Folders and Collections Media Library pages where you are selecting assets by criteria such as upload date, creation date, original filename, file size, etc. This helps you determine the order for setting the `placement` values.

> * The quickest way to manually set contextual metadata for individual assets is by clicking each asset and then setting the context key and value in the Preview pane on the right side of the Media Library. If the Preview pane is closed, click the **Open Preview** button&nbsp; to display it.

### Including 360 spin sets in a generated Product Gallery
To include a 360 spin set in your Product Gallery, you must define both a unique tag and a corresponding contextual metadata key to indicate that assets with this tag should be recognized by the Product Gallery as `mediaType: "spin"`.

1. Apply a unique tag to all of the assets that make up a specific 360 spin set. You can do this easily from the Media Library, by selecting all of the assets, and then selecting the **Tag** option from the asset toolbar to add the same tag to all selected assets.
2. Apply a contextual metadata entry to all of the assets that make up the 360 spin set, with a key called `spinset_tag` and a value matching the unique tag value you set in step 1. You can do this easily from the Media Library, by selecting all of the assets, and then selecting the **Edit Contextual Metadata** option from the asset toolbar to add the same contextual key and value to all selected assets.
3. Follow the general instructions for [Generating Product Gallery code for Media Library assets](#generating_product_gallery_code_for_media_library_assets). When selecting the assets to include in the Product Gallery, it's enough to select any **one** of the assets from your spin set.  Because that asset includes the `spinset_tag` contextual metadata key, this instructs the Product Gallery generator to include all assets with the specified tag as part of a single `mediaType: "spin"` asset.  

## Responsive widget

The Product Gallery widget itself is also responsive to the available width of the user's view port (browser or mobile device). The breakpoints below are matched against the viewport width. By default, the Product Gallery widget has a single `viewportBreakpoint` set for a width of 520 pixels, in effect creating 2 viewing modes as follows:

* *Width over 520 pixels*: A thumbnail styled carousel located on the left of the main viewer (the default main widget configuration).
* *Width up to 520 pixels*: A thumbnail styled carousel located below the main viewer.

You can set your own view port breakpoints for the Product Gallery widget by overriding the `viewportBreakpoints` parameter. This parameter accepts an array of [BreakpointProp](product_gallery_reference#breakpointprops) objects, where each object in the array defines the widget configuration settings for a specified width or less. The main widget configuration is used when the widget has a width larger than the largest given breakpoint in the array. 

For example, to have 3 different viewing modes for the Product Gallery widget as follows:

* *over 600 pixels*: a thumbnail styled carousel located to the left of the main viewer
* *up to 600 pixels*: a thumbnail styled carousel located below the main viewer
* *up to 300 pixels*: an indicator styled carousel located below the main viewer with navigation buttons always enabled

```js
var myGallery = cloudinary.galleryWidget({
  container: "#my-gallery",
  cloudName: "demo",
  mediaAssets: [{ tag: "bag" }],
  carouselStyle: "thumbnails",   // default value: included for clarity
  carouselLocation: "left",     // default value: included for clarity
  viewportBreakpoints: [
  { breakpoint: 600, carouselStyle: "thumbnails", carouselLocation: "bottom" },
  { breakpoint: 300, carouselStyle: "indicators", carouselLocation: "bottom", navigation: "always" } ]
});
myGallery.render();
```

> **NOTE**: The widget fills the width of its containing element (see [Sizing and responsiveness](#sizing_and_responsiveness)), and assets within it adjust to that width. For more information, see [Responsive assets](#responsive_assets).

## Cloudinary video player

The Product Gallery also supports using the [Cloudinary Video Player](#cloudinary_video_player) to play videos, instead of using the default HTML5 video player. The Cloudinary Video Player is a JavaScript-based video player bundled with many valuable customization and integration capabilities, and is monetization and analytics-ready. 

To use the Cloudinary Video Player within the Product Gallery set the `playerType` property of the `videoProps` parameter to 'cloudinary'. This is a global setting for the Product Gallery and affects all videos played within the Product Gallery.

For example, to use the Cloudinary Video Player to play all the video assets:

```js
const myGallery= cloudinary.galleryWidget({ 
  container: "#my-gallery", 
  cloudName: "demo", 
  mediaAssets: [
    { publicId: "dog", mediaType: "video" },
    { publicId: "cat", mediaType: "video" }
  ],
  videoProps: { playerType: "cloudinary" }  
});
```

### Cloudinary Video Player configuration options

You can configure and customize the Cloudinary Video Player for the Product Gallery widget by also including any of the [Video Player configuration options](video_player_api_reference#configuration_options) in the `videoProps` parameter. All the configuration options added to the `videoProps` parameter will affect all the videos played within the Product Gallery.

For example, to only show a larger central play button when a video is initially loaded, include the `bigPlayButton` parameter set to 'init':

```js
const myGallery = cloudinary.galleryWidget({ 
  container: "#my-gallery", 
  cloudName: "demo", 
  mediaAssets: [{ publicId: "dog", mediaType: "video" }],
  videoProps: {
    playerType: "cloudinary",
    bigPlayButton: "init"
  }  
});
```

### Cloudinary Video Player source options

You can also individually configure each of the video assets (sources) you display within the Product Gallery by including any of the [Video Player source options](video_player_api_reference#source) within the `videoPlayerSource` property for each of the video assets given in the `mediaAssets` parameter. 

For example, to configure [adaptive streaming](video_player_hls_dash) options for playing the "dog" video, with `hls` as the primary format and `dash` as a fallback option for browsers that don't support HLS: 

```js
const myGallery = cloudinary.galleryWidget({ 
  container: "#my-gallery", 
  cloudName: "demo", 
  mediaAssets: [{ 
    publicId: "dog", 
    mediaType: "video",
    videoPlayerSource: { 
      sourceTypes: ["hls", "dash"], 
      sourceTransformation: { 
        "hls": [{ streaming_profile: "hd_hls" }], 
        "dash": [{ streaming_profile: "hd_dash" }],
      } 
    }
  }],
  videoProps: {
    playerType: "cloudinary"
  }  
});
```

> **NOTE**: The example above assumes that the streaming profiles and adaptive streaming format were already generated with an eager transformation, ensuring that all required files and video representations are ready to be delivered upon request. For more details, see the [HLS and MPEG-DASH adaptive streaming](video_player_hls_dash) documentation.

### Cloudinary Video Player interactive video example

The following is an example of using the [Interactive Video](video_player_interactive_videos) feature of the Cloudinary Video Player in the Product Gallery. Using the `mediaAssets` parameter, the video is configured with 2 clickable interaction areas that each play a different zoomed in version of the video, and the `videoProps` parameter includes the theme and layout definitions for displaying the interactive functionality:

```js
const myGallery = cloudinary.galleryWidget({ 
  container: "#my-gallery", 
  cloudName: "demo", 
  mediaAssets: [{ 
    publicId: "docs/my_video", 
    mediaType: "video",
    videoPlayerSource: { 
      interactionAreas: {
        enable: true,
        template:  [
            {
              left : 10 ,
              top: 10,
              width: 80,
              height: 40,
              id: 'topSource'
            },
            {
              left : 10 ,
              top: 75,
              width: 80,
              height : 20,
              id: 'bottomSource'
            }
         ],
         onClick: function (event) {
           var sources = {
             topSource : 'https://res.cloudinary.com/demo/video/upload/docs/my_video_top_zoom.mp4',
             bottomSource: 'https://res.cloudinary.com/demo/video/upload/docs/my_video_bottom_zoom.mp4'
           }
           event.zoom(sources[event.item.id]);
         }
      }
    }
  }],
  videoProps: {
    playerType: "cloudinary",
    interactionDisplay: {
      theme:{
        template : 'pulsing' 
      },
      layout: {
        enable: true ,
        showAgain: true,
      }
    }
  }  
});
```

## Gallery events

You can register to a variety of Product Gallery widget events in order to introduce custom behavior in your application or for analytics tracking once your application is deployed. Use the `on` method with an initialized widget to register to a specific event. For example, to register the initialized `myGallery` Product Gallery widget to the `mouseenter` event:

```js
myGallery.on('mouseenter', (data) => {
  console.log('MouseEnter', data);
});
```

For a full listing of available events, see the [Events](product_gallery_reference#events) section in the Product Gallery reference.

## Hover zoom

By default, users zoom by clicking an asset. To zoom when the user hovers over an asset instead (desktops only), set `trigger` to `"hover"` in the `zoomProps` object:

```js
var myGallery = cloudinary.galleryWidget({
  container: "#my-gallery",
  cloudName: "demo",
  mediaAssets: [{ tag: "bag" }],
  zoomProps: { type: "inline", trigger: "hover" }
});
myGallery.render();
```

See [ZoomProps](product_gallery_reference#zoomprops) for the other zoom options.

## Multiple zoom

If you have very high resolution images, you may want to enable the widget with multiple zoom steps to allow your users to see the fine detail in your images. The multi-zoom functionality is only available for the 'popup' type zoom option, and you can set the number of zoom steps between 0 and 5, where each step zooms in according to the value of the `level` property. You can also limit the number of steps, so as not to zoom in beyond the original image size, with the `stepLimit` boolean property.

For example:

```js
var myGallery = cloudinary.galleryWidget({
  container: "#my-gallery",
  cloudName: "demo",
  mediaAssets: [{ tag: "shoes_product_gallery_demo" }],
  zoom: true,    // for demonstration purposes, true is the default value anyway
  zoomProps: {
    type: "popup",
    steps: 3,
    stepLimit: true,
    level: 1.3 // each step zooms in another 130%
  }
});
myGallery.render();
```

> **NOTES**:
>
> * For the best user experience, this feature should only be used when displaying high resolution images, as zooming in on a low resolution image will appear blurry and unclear.

> * The zoom popup covers the whole screen area, full screen, with +/- buttons that let the user zoom in and out (mobile devices use pinch to zoom, and the +/- buttons aren't displayed).

> * After zooming in, the user can drag the zoomed image to see all parts of the image - only a partial view of the image may be shown on screen each time as the image may be bigger than the screen size.

## Integrating with Google Tag Manager

If you have integrated Google Tag Manager on your page, you can tell the Product Gallery widget to update Google Tag Manager's `dataLayer` array whenever an [event](product_gallery_reference#events) is triggered by including the `analytics` boolean parameter set to `true`. For example:

```js
var myGallery = cloudinary.galleryWidget({
  container: "#my-gallery",
  cloudName: "demo",
  mediaAssets: [{ tag: "bag" }],
  analytics: true
});
myGallery.render();
```

> **NOTE**: Requires [Google Tag Manager](https://developers.google.com/tag-manager/devguide) already integrated on the page.

## Accessibility

### Accessible navigation

The Product Gallery enables keyboard accessibility, attending to users who only use a keyboard (unable to use a mouse) or are visually impaired and use a keyboard and a screen reader. Product Gallery end users can use the following keyboard actions as set by accessibility standards:

* **Tab** and **Shift+Tab** to navigate forwards and backwards
* **Enter** to view an asset or zoom
* **Esc** to exit zoom
* **Spacebar** to play/pause videos

Cloudinary recommends the following best practice configuration settings for the most 'accessible' experience:

* `displayProps: {mode: "expanded"}` - in expanded mode the focus area is more visually prominent. Note the trade-off: the `top` and `bottom` values of `carouselLocation` aren't supported in expanded mode.
* `zoomProp: {type: "popup"}` - zoom appears in a pop-up box.
* `videoProps: {controls: "play"}` - displays only the play/pause video controls.

### Accessible text

The Product Gallery adds alt texts to each asset for enhancing SEO and enabling screen readers. The alt text can be configured via the `accessibilityProps` parameter, which receives an object detailing the source of the alt text string to use for each asset. The Product Gallery can be configured to take this string either from an asset's [Contextual metadata](dam_manage_individual_assets#setting_contextual_metadata_values) field, or from an asset's [Structured metadata](dam_manage_individual_assets#setting_structured_metadata_values) field. If neither of these options is configured, the gallery will default to adding a string to the alt text of each asset in the form of "Gallery asset n of m".

The `AccessibilityProps` object includes the following properties:

* `mediaAltSource` - One of:
    * `contextual`: use the value of a Contextual metadata field for each asset, as given by the **key** passed in the 'mediaAltId' property.
    * `metadata`: use the value of a Structured metadata field for each asset as given by the **external\_id** passed in the 'mediaAltId' property.
    * `auto`: (default) use the order of the asset within the gallery using the template: "Gallery asset n of m".
* `mediaAltId` - Either the **key** of a Contextual metadata key-value pair, or the **external_id** of a Structured metadata field.

For example:

```js
var myGallery = cloudinary.galleryWidget({
  container: "#my-gallery",
  cloudName: "demo",
  mediaAssets: [{ tag: "shoes" }],
  accessibilityProps: {
    mediaAltSource: "metadata", 
    mediaAltId: "alt_id"
  }
});
myGallery.render();
```

> **NOTE**: Text accessibility with a `mediaAltSource` of 'contextual' or 'metadata' only works when adding `mediaAssets` with 'tag', and not individually with 'publicId' (you can add the [altText](product_gallery_reference#asset) property for each individual asset you add)).



#### Sample app: Product Gallery accessibility
Check out this [code on GitHub](https://github.com/cloudinary-devs/accessible-product-gallery) that demonstrates the Product Gallery's accessibility features. 

> **TIP**: This sandbox parallels the steps shown in the [Product Gallery accessibility](product_gallery_accessibility_tutorial) video tutorial.


## Product Gallery tips and considerations

* The Product Gallery widget only displays media assets that were uploaded as delivery [type](control_access_to_media) `upload`.
* Take note of any special [configurations parameters](cloudinary_sdks#configuration_parameters) you may need to add when you [initialize](#3_initialize_the_product_gallery_widget) the Product Gallery widget, for example if you have a [private CDN distribution or a custom delivery hostname (CNAME)](advanced_url_delivery_options#private_cdns_and_custom_delivery_hostnames_cnames).
* The Product Gallery widget is incompatible with the [Strict Transformations](control_access_to_media#strict_transformations) feature due to the number of transformations that need to be generated on the fly. A possible workaround is to navigate to **Settings > Security > Allowed strict referral domains** in your [Console Settings](https://console.cloudinary.com/app/settings) and add your domain to the list.
* For best results, and depending on the assets you want to display, you may want to use the 'fill' crop mode and set the correct aspect ratio (especially for multi-columns expanded [mode](#display_mode)).
* Consider overriding the [default gravity](#applying_transformations) parameter to use `auto` gravity (see [Automatic cropping](image_automatic_gravity) for more details).
* In order to comply with [Google autoplay policy changes](https://developers.google.com/web/updates/2017/09/autoplay-policy-changes):
    * With video autoplay in **classic** [mode](#display_mode), a video will have sound muted by default if the video is the first asset presented, regardless of the value of the `sound` parameter in the [VideoProps](product_gallery_reference#videoprops) object. 
    * With video autoplay in **expanded** [mode](#display_mode), all videos will have sound muted by default regardless of the value of the `sound` parameter in the [VideoProps](product_gallery_reference#videoprops) object.
* Transformation vs bandwidth trade-off: By default, the Product Gallery widget is optimized for bandwidth savings by dynamically transforming assets to minimize file size while delivering the best image to the requesting device/browser, at a cost of using up a large number of transformations. If you want to reduce the number of transformations used at the cost of increasing bandwidth usage, you can:
    * Set a larger value for the [imageBreakpoints](#responsive_assets) parameter to reduce the number of images generated.
    * Set a fixed width for your Product Gallery [container](#2_add_a_containing_element_for_the_widget) element.
    * Override the values of the [default transformations](#applying_transformations) for one or more of `dpr`, `fetch_format`, `quality`, to reduce the number of transformations needed.
    * Set the [placeholderImage](product_gallery_reference#widget_parameters) parameter to false. This parameter determines whether to load and display a low-quality blurred placeholder image while waiting for a higher quality image, instead of displaying a loading spinner (which results in a better user experience for a person on a slow connection).

> **See also**:
>
> For details on the available parameters, types, ENUMS, events, and instance methods, see the [Product Gallery reference](product_gallery_reference).

