---
title: "Popovers and overlays"
description: "Open a native popover under a clicked grid item and keep it attached while the grid scrolls."
canonical_url: "https://vvirtual-grid.netlify.app/guides/popovers"
---
# Popovers and overlays

> Open a native popover under a clicked grid item and keep it attached while the grid scrolls.

In this guide you open a native popover under the item a user clicks, and keep it attached while the grid scrolls.

The grid renders only the items near the viewport. Once the clicked item scrolls out, its element is removed from the DOM, and a popover attached to that element loses its position. Instead, you ask the grid for the item's rectangle by index. The grid computes it from the item's position in the list, so it works whether or not the item is rendered.

A native popover is an element with the `popover` attribute. The browser puts it in the top layer when you call `showPopover()`, so it draws above the page and the scroll container does not clip it.

<popover-demo>



</popover-demo>

In the demo, the popover keeps following item 4,200 after you scroll far enough that the item is no longer in the DOM.

## Build it

<steps level="3">

### Mark each item with its index

Add `:data-index="index"` to the root element of both the `default` and `placeholder` slots. The grid gives you `index` in the slot. The attribute lets you find the item from a DOM event later.

The script defines the items, the provider and the grid ref.

```vue
<script setup>
import { useTemplateRef } from "vue";
import { createPageProvider } from "vvirtual-grid/vue";

const items = Array.from({ length: 10000 }, (_, i) => ({ title: `Item ${i + 1}` }));
const pageProvider = createPageProvider(items);
const grid = useTemplateRef("grid");
</script>
```

The template adds the index attribute to both slots. The grid uses the scroll container, column tracks and probe from [Sizing and direction](https://vvirtual-grid.netlify.app/guides/sizing-and-direction).

```vue
<template>
  <div class="h-96 overflow-y-auto">
    <VirtualGrid
      ref="grid"
      :length="items.length"
      :page-size="40"
      :page-provider="pageProvider"
      class="grid grid-cols-[repeat(auto-fill,minmax(120px,1fr))] gap-2"
    >
      <template #default="{ item, index, style }">
        <button :style="style" :data-index="index" class="h-16">{{ item.title }}</button>
      </template>

      <template #placeholder="{ index, style }">
        <div :style="style" :data-index="index" class="h-16" />
      </template>
    </VirtualGrid>
  </div>
</template>
```

### Find the clicked index

Listen for `click` once on `<VirtualGrid>`. One listener covers every item, so the items need no handlers of their own. In the handler, walk up from `event.target` to the nearest element with a `data-index` attribute and read it.

```ts
function indexFromEvent(event: Event) {
  const item = (event.target as Element).closest("[data-index]");
  return item ? Number((item as HTMLElement).dataset.index) : -1;
}
```

The function returns `-1` when the click did not land on an item, for example on the gap between two items.

### Create one rectangle query

`getItemRect` takes a query object. You set `index`, `layout` and `root` on it, and the function writes the item's rectangle into `query.rect`. Create the query once with `createRectQuery`, outside the handlers, and change its fields before each call.

```ts
import { createRectQuery } from "vvirtual-grid/primitives";

const query = createRectQuery();
```

The function writes into an object you own, instead of returning a new one, because `viewport-scroll` fires on every scroll event. A new rectangle per event is garbage the browser must collect while the user scrolls. Reusing one object avoids that. It is the same idea as an output parameter in a C API, `get_rect(index, &rect)`.

Set `query.root` to `grid.value.$el`. With a `root`, the rectangle is relative to the viewport, like `getBoundingClientRect()`. This costs one layout read of the grid's first element. Without a `root`, the rectangle is relative to item 0 and the call reads nothing from the DOM.

### Position the popover from the rectangle

Write a `place()` function that fills the query, calls `getItemRect`, and moves the popover under the item. The function uses the `grid` ref from [Mark each item with its index](#mark-each-item-with-its-index) and the query from [Create one rectangle query](#create-one-rectangle-query).

```ts
import { ref, useTemplateRef } from "vue";
import { getItemRect } from "vvirtual-grid/primitives";

const popover = useTemplateRef("popover");
const anchored = ref(-1);

function place() {
  if (anchored.value < 0 || !grid.value || !popover.value) return;
  query.root = grid.value.$el;
  query.index = anchored.value;
  query.layout = grid.value.measurement;
  if (!getItemRect(query)) return;
  popover.value.style.translate = `${query.rect.left}px ${query.rect.bottom}px`;
}
```

The popover needs `position: fixed`, because the rectangle holds viewport coordinates. Also reset `margin` and `inset`, which the browser sets on every popover to center it.

```vue
<template>
  <div ref="popover" popover style="position: fixed; inset: 0 auto auto 0; margin: 0">
    Item {{ anchored }}
  </div>
</template>
```

`getItemRect` returns `false` and leaves `query.rect` unchanged when `measurement` is not ready or nothing is rendered yet. The `place()` function stops in that case.

### Call `place()` when the position can change

The popover must move in three situations. Call `place()` in each of them:

- When it opens, for the first position.
- On `viewport-scroll`, because every item moved on screen.
- On `layout-change`, because the item size, the gap or the number of columns changed.

```vue
<template>
  <div class="h-96 overflow-y-auto">
    <VirtualGrid
      ref="grid"
      :length="items.length"
      :page-size="40"
      :page-provider="pageProvider"
      @click="open"
      @viewport-scroll="place"
      @layout-change="place"
      class="grid grid-cols-[repeat(auto-fill,minmax(120px,1fr))] gap-2"
    >
      <!-- the default, placeholder and probe slots -->
    </VirtualGrid>
  </div>
</template>
```

```ts
function open(event: MouseEvent) {
  const index = indexFromEvent(event);
  if (index === -1) return;
  anchored.value = index;
  place();
  popover.value.showPopover();
}
```

### Check that it follows the item

Click an item, then scroll the container until that item is out of sight. The popover keeps moving with the item's position and moves outside the container.

To see that the item left the DOM, open the browser's Elements panel and expand the grid. It has no child with the item's `data-index`, and the popover is still in the page.

</steps>

## Hide the popover when the item is out of view

The rectangle stays valid after the item scrolls out, so the popover moves outside the scroll container and may overlap other parts of the page. To close it instead, compare the rectangle with the scroll container's bounds at the end of `place()`. Give the scroll container a template ref named `scroller`.

```ts
const scroller = useTemplateRef("scroller");

function place() {
  if (anchored.value < 0 || !grid.value || !popover.value || !scroller.value) return;
  query.root = grid.value.$el;
  query.index = anchored.value;
  query.layout = grid.value.measurement;
  if (!getItemRect(query)) return;
  const bounds = scroller.value.getBoundingClientRect();
  if (query.rect.bottom < bounds.top || query.rect.top > bounds.bottom) {
    popover.value.hidePopover();
    return;
  }
  popover.value.style.translate = `${query.rect.left}px ${query.rect.bottom}px`;
}
```

The code reads every rectangle before it writes the `translate` style. Reading a layout value after a style write forces the browser to recompute layout at once, which slows every scroll event.

## Let CSS place the popover with anchor positioning

In browsers that support [CSS anchor positioning](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_anchor_positioning), the browser can place the popover, with no `place()` call on scroll. The browser needs the item to be in the DOM, so this works only while the anchored item is rendered.

`createItemTracker` tells you when an element starts or stops rendering an index. Set `anchor-name` on the element in `onBind`, and close the popover in `onUnbind`.

```ts
import { createItemTracker } from "vvirtual-grid/primitives";

const track = createItemTracker({
  onBind: (index, element) => {
    element.style.anchorName = index === anchored.value ? "--item" : "";
  },
  onUnbind: (index) => {
    if (index === anchored.value) popover.value.hidePopover();
  },
});
```

```css
[popover] {
  position-anchor: --item;
  inset: auto;
  margin: 0;
  top: anchor(bottom);
  left: anchor(left);
}
```

Add `@render="track(grid.$el)"` to `<VirtualGrid>`, so the tracker compares the rendered elements after each patch.

The tracker reports changes in what the grid renders. It does not notice when `anchored` changes. To anchor an item that is already rendered, set `anchor-name` yourself, and clear it on the previous item.

```ts
function anchor(index: number) {
  const root: HTMLElement = grid.value.$el;
  const previous = root.querySelector(":scope > [style*='anchor-name']");
  if (previous) (previous as HTMLElement).style.anchorName = "";
  const next = root.querySelector(`:scope > [data-index="${index}"]`);
  if (next) (next as HTMLElement).style.anchorName = "--item";
  anchored.value = index;
}
```

Call `anchor(index)` from the `open` handler in [Call `place()` when the position can change](#call-place-when-the-position-can-change) instead of setting `anchored` directly. It clears the previous element and sets the new one when that element is already rendered.

## Dispatch your own events from the grid

The grid does not emit events for pointer or focus actions on items. A listener on the grid element is the lowest-level hook for those, and you can turn what it reads into an event of your own. For example, to tell other components which item got focus, listen to `focusin`, find the index as in [Find the clicked index](#find-the-clicked-index), and dispatch a `CustomEvent` that carries it.

```ts
function onFocusIn(event: FocusEvent) {
  const index = indexFromEvent(event);
  if (index === -1) return;
  grid.value.$el.dispatchEvent(new CustomEvent("item-focus", { detail: index }));
}
```

Add `@focusin="onFocusIn"` to `<VirtualGrid>`. Other code listens on the grid element with `grid.value.$el.addEventListener("item-focus", (event) => event.detail)`. The same pattern works for `pointerover` and `contextmenu`.

To place an overlay with a library instead of your own `translate`, read [Position with Floating UI](https://vvirtual-grid.netlify.app/guides/floating-ui).


## Sitemap

See the full [sitemap](https://vvirtual-grid.netlify.app/sitemap.md) for all pages.
