---
title: "Open from code"
description: "useImageViewer() opens any list of images, with or without thumbnails on the page."
canonical_url: "https://kukson777.github.io/nuxt-image-viewer/docs/guide/open-from-code"
---
# Open from code

> useImageViewer() opens any list of images, with or without thumbnails on the page.

`useImageViewer()` is auto-imported. It opens the viewer with your own list of images, scrolls it and tells you where it is.

```ts
const viewer = useImageViewer()

await viewer.open(
  [
    { src: '/photos/valley.jpg', width: 3000, height: 1500, caption: 'Valley' },
    { src: '/photos/ocean.jpg', width: 2400, height: 1600, caption: 'Ocean' },
  ],
  1, // start index
  { loop: false, bgOpacity: 1 }, // options for this viewer only
)
```

<open-from-code-demo>



</open-from-code-demo>

## Items

Only `src` is required.

<field-group>
<field name="src" type="string" :required="true">

The full image.

</field>

<field name="width / height" type="number">

Natural size. Without it the image is loaded and measured first, so the viewer opens a moment later — pass it when you know it.

</field>

<field name="thumb" type="string">

A copy shown at once while `src` loads. Defaults to `element.currentSrc`, otherwise `src`.

</field>

<field name="element" type="HTMLElement">

The page element the image opens from and closes back into. Without it the viewer fades in and out.

</field>

<field name="alt" type="string">

Alternative text. Defaults to the `alt` of `element`.

</field>

<field name="caption" type="string">

Caption under the image.

</field>
</field-group>

## Flying from your own thumbnails

Pass the elements and the viewer animates from them exactly like it does for `<ZoomImage>`:

```vue
<script setup lang="ts">
const viewer = useImageViewer()
const thumbs = useTemplateRef<HTMLImageElement[]>('thumbs')

function open(index: number) {
  viewer.open(photos.map((photo, i) => ({ ...photo, element: thumbs.value?.[i] })), index)
}
</script>

<template>
  <button v-for="(photo, i) in photos" :key="photo.src" @click="open(i)">
    <img ref="thumbs" :src="photo.thumb" :alt="photo.caption">
  </button>
</template>
```

## Controlling an open viewer

```ts
const { isOpen, index, items, next, prev, goTo, close } = useImageViewer()

watch(index, i => history.replaceState(null, '', `#photo-${i}`))

goTo(3) // takes the shortest way round the endless strip
close() // with the animation back into the page
```

See the full [API reference](https://kukson777.github.io/nuxt-image-viewer/docs/api/use-image-viewer).

<note>

The viewer exists only in the browser. On the server `useImageViewer()` returns a harmless stub: `isOpen` is `false` and the methods do nothing, so it's safe to call in `setup`.

</note>


## Sitemap

See the full [sitemap](https://kukson777.github.io/nuxt-image-viewer/sitemap.md) for all pages.
