Skip to content

Virtual Elements

A floating element can be positioned relative to a virtual reference element instead of a real one.

This enables features such as positioning context menus, following the cursor, range selections, etc.

Usage

The most basic virtual element is a plain object that has a getBoundingClientRectgetBoundingClientRect method, which mimics a real element’s one:

// A virtual element that is 20 x 20 px starting from (0, 0)
const virtualEl = {
  getBoundingClientRect() {
    return {
      x: 0,
      y: 0,
      top: 0,
      left: 0,
      bottom: 20,
      right: 20,
      width: 20,
      height: 20,
    };
  },
};
 
computePosition(virtualEl, floatingEl);
// A virtual element that is 20 x 20 px starting from (0, 0)
const virtualEl = {
  getBoundingClientRect() {
    return {
      x: 0,
      y: 0,
      top: 0,
      left: 0,
      bottom: 20,
      right: 20,
      width: 20,
      height: 20,
    };
  },
};
 
computePosition(virtualEl, floatingEl);

A point reference, such as a mouse event, is one such use case:

function onClick({clientX, clientY}) {
  const virtualEl = {
    getBoundingClientRect() {
      return {
        width: 0,
        height: 0,
        x: clientX,
        y: clientY,
        top: clientY,
        left: clientX,
        right: clientX,
        bottom: clientY,
      };
    },
  };
 
  computePosition(virtualEl, floatingEl).then(({x, y}) => {
    // Position the floating element relative to the click
  });
}
 
document.addEventListener('click', onClick);
function onClick({clientX, clientY}) {
  const virtualEl = {
    getBoundingClientRect() {
      return {
        width: 0,
        height: 0,
        x: clientX,
        y: clientY,
        top: clientY,
        left: clientX,
        right: clientX,
        bottom: clientY,
      };
    },
  };
 
  computePosition(virtualEl, floatingEl).then(({x, y}) => {
    // Position the floating element relative to the click
  });
}
 
document.addEventListener('click', onClick);

contextElement

This property is useful if your getBoundingClientRectgetBoundingClientRect method is derived from a real element, to ensure clipping and position update detection works as expected.

const virtualEl = {
  getBoundingClientRect() {
    return {
      // ...
    };
  },
  contextElement: document.querySelector('#context'),
};
const virtualEl = {
  getBoundingClientRect() {
    return {
      // ...
    };
  },
  contextElement: document.querySelector('#context'),
};

getClientRects

This property is useful when using range selections and the inline()inline() middleware.

const virtualEl = {
  getBoundingClientRect: () => range.getBoundingClientRect(),
  getClientRects: () => range.getClientRects(),
};
const virtualEl = {
  getBoundingClientRect: () => range.getBoundingClientRect(),
  getClientRects: () => range.getClientRects(),
};