Skip to content

Hover card ​

A preview card that appears when the pointer rests on or keyboard focus reaches a link, built on Bootstrap Popover.

  • Version 1.0.0
  • Bootstrap 5.3+
  • Requires Bootstrap CSS + Bootstrap JS bundle
  • Source on GitHub

Installation ​

bash
npx bootcn add hover-card
bash
pnpm dlx bootcn add hover-card
bash
yarn dlx bootcn add hover-card
bash
bunx --bun bootcn add hover-card

The CLI also installs the design tokens and these components: avatar. It prints the <link> and <script> tags to add to your layout.

Usage ​

Use a hover card for a preview of something behind a link, such as a profile. The link must still work on its own: touch devices and some users never see the card. The content is copied from a <template> and passes through Bootstrap's HTML sanitizer.

JavaScript API ​

  • data-bootcn-hover-card="<template id>" on the trigger: the card shows the content of that <template>.
  • data-bootcn-placement (optional): top, right, bottom (default) or left.
  • Bootcn.hoverCard.init() / destroy(): add or remove the delegated listeners (and dispose open cards).

Accessibility ​

  • It opens on keyboard focus as well as hover, and Escape closes it (WCAG 1.4.13).
  • It stays open while the pointer moves from the link onto the card.
  • The card is linked to the trigger with aria-describedby (Bootstrap), so screen readers read it as the link's description. Do not put links or buttons inside it: they cannot be reached with the keyboard.

Dependencies ​

  • Bootstrap 5.3+ CSS and the JS bundle.
  • themes/tokens/tokens.css.
  • The avatar component.

Source ​

The exact files the CLI installs (hover-card@1.0.0). View on GitHub · Report an issue

html
<p>
  Maintained by
  <a
    href="#profile"
    class="bootcn-hover-card__trigger"
    data-bootcn-hover-card="bootcn-hover-card-profile"
    >@acme</a
  >
  and contributors.
</p>

<template id="bootcn-hover-card-profile">
  <div class="bootcn-hover-card__body">
    <span class="bootcn-avatar" aria-hidden="true"
      ><span class="bootcn-avatar__fallback">AC</span></span
    >
    <div>
      <p class="bootcn-hover-card__name">Acme</p>
      <p class="bootcn-hover-card__text">Open-source tools for teams who build for the web.</p>
      <p class="bootcn-hover-card__meta">Joined March 2021</p>
    </div>
  </div>
</template>
css
.bootcn-hover-card {
  --bs-popover-max-width: 20rem;
  --bs-popover-bg: var(--bootcn-background);
  --bs-popover-border-color: var(--bootcn-border-color);
  --bs-popover-border-radius: var(--bootcn-radius-lg);
  --bs-popover-inner-border-radius: calc(var(--bootcn-radius-lg) - 1px);
  --bs-popover-body-padding-x: 1rem;
  --bs-popover-body-padding-y: 1rem;
  --bs-popover-body-color: var(--bootcn-foreground);
  --bs-popover-font-size: 0.875rem;

  box-shadow: var(--bootcn-shadow-md);
}

.bootcn-hover-card__body {
  display: flex;
  gap: 1rem;
}

.bootcn-hover-card__name {
  margin: 0;
  font-weight: 600;
}

.bootcn-hover-card__text {
  margin: 0.25rem 0 0;
}

.bootcn-hover-card__meta {
  margin: 0.5rem 0 0;
  color: var(--bootcn-muted-foreground);
  font-size: 0.75rem;
}

.bootcn-hover-card__trigger {
  font-weight: 500;
}
js
(function () {
  'use strict';

  const ns = (window.Bootcn = window.Bootcn || {});
  if (ns.hoverCard) return; // already loaded: idempotent

  const SELECTOR = '[data-bootcn-hover-card]';
  const OPEN_DELAY = 300;
  const CLOSE_DELAY = 150;
  const timers = new WeakMap();
  let listening = false;

  function plugin() {
    return window.bootstrap && window.bootstrap.Popover;
  }

  function instanceFor(trigger) {
    const Popover = plugin();
    const existing = Popover.getInstance(trigger);
    if (existing) return existing;
    const template = document.getElementById(trigger.getAttribute('data-bootcn-hover-card'));
    return new Popover(trigger, {
      trigger: 'manual',
      html: true,
      placement: trigger.getAttribute('data-bootcn-placement') || 'bottom',
      customClass: 'bootcn-hover-card',
      content: template ? template.innerHTML : '',
    });
  }

  function tipOf(trigger) {
    const id = trigger.getAttribute('aria-describedby');
    return id ? document.getElementById(id) : null;
  }

  function schedule(trigger, action, delay) {
    clearTimeout(timers.get(trigger));
    timers.set(
      trigger,
      setTimeout(function () {
        const instance = instanceFor(trigger);
        if (action === 'show') instance.show();
        else instance.hide();
      }, delay),
    );
  }

  // WCAG 1.4.13: the card stays open while the pointer is over it.
  function onOver(event) {
    const trigger = event.target.closest(SELECTOR);
    if (trigger) {
      schedule(trigger, 'show', OPEN_DELAY);
      return;
    }
    const tip = event.target.closest('.bootcn-hover-card');
    if (!tip) return;
    const owner = document.querySelector('[aria-describedby="' + tip.id + '"]');
    if (owner) clearTimeout(timers.get(owner));
  }

  function onOut(event) {
    const trigger = event.target.closest(SELECTOR);
    if (trigger && !trigger.contains(event.relatedTarget)) {
      const tip = tipOf(trigger);
      if (!tip || !tip.contains(event.relatedTarget)) schedule(trigger, 'hide', CLOSE_DELAY);
      return;
    }
    const tip = event.target.closest('.bootcn-hover-card');
    if (!tip || tip.contains(event.relatedTarget)) return;
    const owner = document.querySelector('[aria-describedby="' + tip.id + '"]');
    if (owner && !owner.contains(event.relatedTarget)) schedule(owner, 'hide', CLOSE_DELAY);
  }

  function onFocusIn(event) {
    const trigger = event.target.closest && event.target.closest(SELECTOR);
    if (trigger) schedule(trigger, 'show', 0);
  }

  function onFocusOut(event) {
    const trigger = event.target.closest && event.target.closest(SELECTOR);
    if (trigger) schedule(trigger, 'hide', 0);
  }

  // WCAG 1.4.13: dismissible without moving the pointer or focus.
  function onKeydown(event) {
    if (event.key !== 'Escape') return;
    document.querySelectorAll(SELECTOR + '[aria-describedby]').forEach(function (trigger) {
      clearTimeout(timers.get(trigger));
      instanceFor(trigger).hide();
    });
  }

  function init() {
    if (!plugin()) {
      console.error(
        '[bootcn] hover-card: Bootstrap JavaScript is required. Load the Bootstrap bundle (window.bootstrap.Popover) before bootcn hover-card.js.',
      );
      return;
    }
    if (listening) return;
    document.addEventListener('mouseover', onOver);
    document.addEventListener('mouseout', onOut);
    document.addEventListener('focusin', onFocusIn);
    document.addEventListener('focusout', onFocusOut);
    document.addEventListener('keydown', onKeydown);
    listening = true;
  }

  function destroy() {
    if (!listening) return;
    document.removeEventListener('mouseover', onOver);
    document.removeEventListener('mouseout', onOut);
    document.removeEventListener('focusin', onFocusIn);
    document.removeEventListener('focusout', onFocusOut);
    document.removeEventListener('keydown', onKeydown);
    listening = false;
    const Popover = plugin();
    if (!Popover) return;
    document.querySelectorAll(SELECTOR).forEach(function (trigger) {
      const instance = Popover.getInstance(trigger);
      if (instance) instance.dispose();
    });
  }

  ns.hoverCard = { init: init, destroy: destroy };

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', init);
  } else {
    init();
  }
})();

Released under the MIT License. Not affiliated with Bootstrap or shadcn/ui.