@gravatar-com/hovercards

中文文档
0.17.0发布于 2026/10/30GPL-2.0-or-laterTypeScriptESM + CJS零依赖构建来源已验证近 30 天下载 5247

Add profile hovercards to Gravatar images.

原始使用文档
文档目录14 节
  1. Table of Contents
  2. Installation
  3. Install with NPM or Yarn
  4. Install with UNPKG
  5. Vanilla JavaScript
  6. Usage
  7. API
  8. React
  9. React Component
  10. React Hook
  11. TypeScript
  12. Translations
  13. Contribute to Gravatar Hovercards
  14. License

Gravatar Hovercards

npm build release package size downloads downloads

Gravatar Hovercards is an easy-to-use library that brings Gravatar profiles to your website. It converts static Gravatar images, or any element with the data-gravatar-hash attribute into interactive hovercards.

Table of Contents

Installation

This Gravatar Hovercards library supports both Vanilla JavaScript (including TypeScript) and React. Install it via Yarn, NPM, or directly include it via UNPKG CDN.

Install with NPM or Yarn

Add the package to your project:

npm install @gravatar-com/hovercards

or

yarn add @gravatar-com/hovercards

For React, also add react and react-dom (v16.8.0 or above):

npm install add react react-dom @gravatar-com/hovercards

Install with UNPKG

For Vanilla JavaScript, import the library as shown below:

<!-- Import the hovercard styles -->
<link rel="stylesheet" href="https://unpkg.com/@gravatar-com/[email protected]/dist/style.css">

<!-- Import the hovercards library -->
<script src="https://unpkg.com/@gravatar-com/[email protected]" defer></script>

<script>
  // The library is accessible as a global variable
  console.log( Gravatar );
</script>

For React, import the library as shown below:

<link rel="stylesheet" href="https://unpkg.com/@gravatar-com/[email protected]/dist/style.css">

<!-- Ensure React and ReactDOM are imported before the library -->
<script src="https://unpkg.com/[email protected]" defer></script>
<script src="https://unpkg.com/[email protected]" defer></script>
<!-- Import the React hovercards library -->
<script src="https://unpkg.com/@gravatar-com/[email protected]/dist/index.react.umd.js" defer></script>

<script>
  console.log( Gravatar );
</script>

Replace x.x.x with the latest version number. Please refer to UNPKG's documentation for more information.

Vanilla JavaScript

Usage

You can add hovercards to your page by either using existing Gravatar images, or by adding a data attribute to any element.

1. Gravatar Images

Ensure your page includes Gravatar images. The URLs of these images should contain hashed email addresses. For more information, refer to the gravatar images implementation guide.

For example:

<div id="container">
    <img id="avatar-1" src="https://www.gravatar.com/avatar/<HASHED_EMAIL_ADDRESS>" alt="Gravatar Image">
    <img id="avatar-2" src="https://www.gravatar.com/avatar/<HASHED_EMAIL_ADDRESS>" alt="Gravatar Image">

    <!-- Image URL with specified parameters -->
    <img id="avatar-3" src="https://www.gravatar.com/avatar/<HASHED_EMAIL_ADDRESS>?s=250&d=retro&r=pg" alt="Gravatar Image">
</div>

These can be turned into hovercards:

import { Hovercards } from '@gravatar-com/hovercards';
// Import the hovercard styles
import '@gravatar-com/hovercards/dist/style.css';

document.addEventListener( 'DOMContentLoaded', () => {
    // Start the hovercards feature with your preferred settings
    const hovercards = new Hovercards( { /* Options */ } );

    // Make hovercards work on a specific Gravatar image
    hovercards.attach( document.getElementById( 'avatar-1' ) );

    // Alternatively, make hovercards work on all Gravatar images within a specific container
    hovercards.attach( document.getElementById( 'container' ) );

    // If you want hovercards on all Gravatar images across the entire page, use `document.body` as the target
    hovercards.attach( document.body );

    // You can exclude certain Gravatar images from hovercards by using `ignoreSelector`
    hovercards.attach( document.body, { ignoreSelector: '.ignore img[src*="gravatar.com/avatar/"]' } );
} );

2. Elements with data-gravatar-hash Attribute

Alternatively, use the data-gravatar-hash attribute to specify the Gravatar hash for any element. This will automatically be converted into an interactive hovercard.

Note: The data attributes takes priority over the image URL.

For example:

<div id="container">
    <div id="ref-1" data-gravatar-hash="<HASHED_EMAIL_ADDRESS>">@Meow</div>
    <div id="ref-2" data-gravatar-hash="<HASHED_EMAIL_ADDRESS>">@Woof</div>

    <!-- A hash with specified parameters -->
    <div id="ref-3" data-gravatar-hash="<HASHED_EMAIL_ADDRESS>?s=250&d=retro&r=pg">@Haha</div>
</div>

To convert these elements into interactive hovercards:

import { Hovercards } from '@gravatar-com/hovercards';
import '@gravatar-com/hovercards/dist/styles.css';

document.addEventListener( 'DOMContentLoaded', () => {
    // Start the hovercards feature with your preferred settings
    const hovercards = new Hovercards( { /* Options */ } );

    // Attach hovercards on a specific image
    hovercards.attach( document.getElementById( 'ref-1' ) );

    // Attach to all images within a container
    hovercards.attach( document.getElementById( 'container' ) );

    // Attach to all images on the page
    hovercards.attach( document.body );
} );

API

Options

You can pass an object of options to the Hovercards constructor to customize the behavior of your hovercards. The following options are available:

placement: string = 'right-start'

The placement of the hovercard relative to the target element. Possible values are top, bottom, left, right, top-start, top-end, bottom-start, bottom-end, left-start, left-end, right-start, and right-end.

autoFlip: boolean = true

Determines whether the hovercard's placement should automatically flip when there is not enough display space.

autoShift: boolean = true

Determines whether the hovercard's placement should automatically shift when there is not enough display space.

hideOnTargetClick: boolean = false

Hides the hovercard when its trigger element is clicked.

offset: number = 10

The offset of the hovercard relative to the target element, in pixels.

delayToShow: number = 500

The delay in milliseconds before the hovercard is shown.

delayToHide: number = 300

The delay in milliseconds before the hovercard is hidden.

i18n: Record< string, string >

Translated text strings to use instead of the default English.

additionalClass: string = ''

Additional class names to be added to the outermost element of the hovercard. This is useful for customizing the styling of the hovercard.

myHash: string = ''

It enables personalized hovercard features for the current user. It allows displaying customized options like "Edit your profile" when the user's "about me" field is empty on their Gravatar editing page.

onQueryHovercardRef: ( ref: HTMLElement ) => HTMLElement

This callback function is triggered when the library queries a hovercard ref (or a Gravatar image), allowing you to customize the ref element. The function receives the ref element as an argument and should return the modified version of the element.

onFetchProfileStart: ( hash: string ) => void

This callback function is triggered when the library starts fetching a Gravatar profile. It takes the Gravatar hash as a parameter. Note that this function is executed only once per Gravatar hash due to the caching mechanism.

onFetchProfileSuccess: ( hash: string, profileData: ProfileData ) => void

This callback function is triggered when the library successfully fetches a Gravatar profile. It takes the Gravatar hash and the profile data as parameters. Note that this function is executed only once per Gravatar hash due to the caching mechanism.

The profileData parameter is an object that contains the following properties:

interface ProfileData {
    hash: string;
    avatarUrl: string;
    profileUrl: string;
    displayName: string;
    location?: string;
    description?: string;
    jobTitle?: string;
    company?: string;
    headerImage?: string;
    hideDefaultHeaderImage?: boolean;
    backgroundColor?: string;
    verifiedAccounts?: Record< 'label' | 'icon' | 'url' | 'type', string >[];
    contactInfo?: ContactInfo;
    payments?: Payments;
}
onFetchProfileFailure: ( hash: string, error: FetchProfileError ) => void

This callback function is triggered when the library fails to fetch a Gravatar profile. It takes the Gravatar hash and the error as parameters. Note this function is executed only once per Gravatar hash due to the caching mechanism.

The error parameter is an object that contains the following properties:

interface FetchProfileError {
    code: number;
    message: string;
}
onHovercardShown: ( hash: string, hovercard: HTMLDivElement ) => void

This callback function is triggered when the hovercard is shown. It takes the Gravatar hash and the hovercard element as parameters.

onHovercardHidden: ( hash: string, hovercard: HTMLDivElement ) => void

This callback function is triggered when the hovercard is hidden. It takes the Gravatar hash and the hovercard element as parameters.

onCanShowHovercard: ( hash: string ) => bool

This callback function is triggered just before a hovercard is shown, giving you control over the card at runtime. It takes the Gravatar hash and returns a boolean value. If the value returned is false then the card won't be shown.

Methods

The Hovercards class provides the following methods:

(static) createHovercard( profileData: ProfileData, options?: { additionalClass?: string; myHash?: string, i18n?: Record< string, string > } ): HTMLDivElement

This method generates a hovercard element using the provided profile data. It accepts the profileData parameter, which represents the data needed to populate the hovercard, and an optional options object that can include properties such as additionalClass, myHash and i18n. It's useful when you want to display static hovercards on your website.

import { Hovercards } from '@gravatar-com/hovercards';

const hovercard = Hovercards.createHovercard( {
    hash: '...',
    avatarUrl: '...',
    profileUrl: '...',
    displayName: '...',
    description: '...',
    location: '...',
    jobTitle: '...',
    company: '...',
    verifiedAccounts = [ {
        label: '...',
        icon: '...',
        url: '...',
        type: '...',
    } ],
} );

document.getElementById( 'container' ).appendChild( hovercard );
(static) createHovercardSkeleton( options?: { additionalClass?: string } ): HTMLDivElement

This method generates a skeleton hovercard element. It accepts an optional options object that can include the additionalClass property. It's useful when you want to display a loading state while fetching the Gravatar profile.

import { Hovercards } from '@gravatar-com/hovercards';

const hovercardSkeleton = Hovercards.createHovercardSkeleton();

document.getElementById( 'container' ).appendChild( hovercardSkeleton );
(static) createHovercardError( avatarUrl: string, message: string, options?: { additionalClass?: string; avatarAlt?: string; additionalMessage?: string } ): HTMLDivElement

This method generates an error hovercard element. It accepts the avatarUrl parameter, which represents the URL of the avatar image, the message parameter, which represents the error message, and an optional options object that can include properties such as additionalClass, avatarAlt (default: 'Avatar'), among others. It's useful when you want to display an error message when fetching the Gravatar profile fails.

message and avatarAlt are rendered as plain text (HTML is escaped), while additionalMessage is inserted as HTML, so only pass trusted markup to it.

import { Hovercards } from '@gravatar-com/hovercards';

const hovercardError = Hovercards.createHovercardError( 'https://www.gravatar.com/avatar/<HASHED_EMAIL_ADDRESS>', 'Error message' );

document.getElementById( 'container' ).appendChild( hovercardError );
attach( target: HTMLElement, options?: { dataAttributeName?: string; ignoreSelector?: string } ): void

This method attaches the hovercards to the specified target element, thereby enabling the hovercard functionality. It accepts the target parameter, which represents the target element to which the hovercards will be attached, and an optional options object that can include properties such as dataAttributeName and ignoreSelector.

  • dataAttributeName (default: 'gravatar-hash') - The name of the data-* attribute that contains the Gravatar hash. This option is useful when you want to use a custom attribute name instead of data-gravatar-hash. If you want to disable the data-* attribute feature, you can set this option to an empty string.
  • ignoreSelector (default: '') - A query selector that specifies elements to be excluded from displaying hovercards. This option is useful when you want to prevent certain elements from triggering hovercards.

Note: Each attach() call automatically detaches hovercards from their current target before attaching them to the new target.

detach(): void

This method detaches the hovercards from their current target element, thereby disabling the hovercard functionality.

React

This library offers a React component and a hook, their operation is similar to the Vanilla JavaScript version.

React Component

Usage

Here is a basic example:

// Import the React component
import { Hovercards } from '@gravatar-com/hovercards/react';
// Import the hovercard styles
import '@gravatar-com/hovercards/dist/style.css';

function App() {
    // ...

    return (
        <Hovercards>
            { /* Work with Gravatar images */ }
            <img src="https://www.gravatar.com/avatar/<HASHED_EMAIL_ADDRESS>" alt="Gravatar Image" />
            <img src="https://www.gravatar.com/avatar/<HASHED_EMAIL_ADDRESS>" alt="Gravatar Image" />

            { /* Work with elements having `data-gravatar-hash` attribute */ }
            <div data-gravatar-hash="<HASHED_EMAIL_ADDRESS>">@Meow</div>
            <div data-gravatar-hash="<HASHED_EMAIL_ADDRESS>">@Woof</div>
        </Hovercards>
    );
}

Note: The component will create a div container element to wrap all the children. You can customize the container element by using the className or style props.

To attach hovercards to the whole page or a specific element, use the attach prop:

import { Hovercards } from '@gravatar-com/hovercards/react';
import '@gravatar-com/hovercards/dist/style.css';

function App() {
    // ...

    return (
        <>
            <div>
                <img src="https://www.gravatar.com/avatar/<HASHED_EMAIL_ADDRESS>" alt="Gravatar Image" />
                <img src="https://www.gravatar.com/avatar/<HASHED_EMAIL_ADDRESS>" alt="Gravatar Image" />
                <img src="https://www.gravatar.com/avatar/<HASHED_EMAIL_ADDRESS>" alt="Gravatar Image" />
            </div>
            { /* Attach hovercards to the entire page */ }
            <Hovercards attach={ document.body } />
        </>
    );
}

Props

The Hovercards component accepts the following props:

attach?: HTMLElement

This prop specifies the target element to which the hovercards will be attached. It's useful when you want to attach hovercards to an entire page.

dataAttributeName?: string = 'gravatar-hash'

This prop specifies the name of the data-* attribute that contains the Gravatar hash. It's useful when you want to use a custom attribute name instead of data-gravatar-hash. If you want to disable the data-* attribute feature, you can set this prop to an empty string.

ignoreSelector?: string = ''

This prop specifies a query selector that specifies elements to be excluded from displaying hovercards. It's useful when you want to prevent certain elements from triggering hovercards.

className?: string

This prop allows you to specify class names to be added to the container element, which is created by the component to wrap all the children.

style?: React.CSSProperties

This prop allows you to specify styles to be added to the container element, which is created by the component to wrap all the children.

For the remaining props, please refer to the Options section.

React Hook

Usage

Here are some basic examples of how to use the React hook:

import { useEffect, useRef } from 'react';
// Import the React hook
import { useHovercards } from '@gravatar-com/hovercards/react';
// Import the hovercard styles
import '@gravatar-com/hovercards/dist/style.css';

function App() {
    const { attach } = useHovercards( { /* Options */ } );
    const containerRef = useRef();

    useEffect( () => {
        if ( containerRef.current ) {
            attach( containerRef.current );
        }
    }, [ attach ] );

    return (
        <div ref={ containerRef }>
            { /* Work with Gravatar images */ }
            <img src="https://www.gravatar.com/avatar/<HASHED_EMAIL_ADDRESS>" alt="Gravatar Image" />
            <img src="https://www.gravatar.com/avatar/<HASHED_EMAIL_ADDRESS>" alt="Gravatar Image" />

            { /* Work with elements having `data-gravatar-hash` attribute */ }
            <div data-gravatar-hash="<HASHED_EMAIL_ADDRESS>">@Meow</div>
            <div data-gravatar-hash="<HASHED_EMAIL_ADDRESS>">@Woof</div>
        </div>
    );
}

Note: When the component is unmounted, the hook will automatically detach the hovercards from the target element.

You can also use the hook to create a custom component:

import sha256 from 'js-sha256';
import { useEffect, useRef } from 'react';
import { useHovercards } from '@gravatar-com/hovercards/react';
import '@gravatar-com/hovercards/dist/style.css';

// A custom Avatar component for convenience
function Avatar( { email } ) {
    const { attach } = useHovercards();
    const imgRef = useRef();

    useEffect( () => {
        if ( imgRef.current ) {
            attach( imgRef.current );
        }
    }, [ attach ] );

    return (
        <img ref={ imgRef } src={ `https://www.gravatar.com/avatar/${ sha256( email ) }` } alt="Gravatar Image" />
    );
}

Options and Methods

The hook accepts the same options and methods as the Hovercards class. Please refer to the API section for further details.

TypeScript

This library is written in TypeScript and comes with type definitions. You can check the following files for the available types:

Translations

A few items of text are used when displaying a hovercard. The library contains English by default, but you can supply your own translations through the use of the i18n option.

The following phrases are used:

  • Edit your profile →
  • View profile →
  • Contact
  • Send money
  • Sorry, we are unable to load this Gravatar profile.
  • Gravatar not found.
  • This profile is private.
  • Too Many Requests.
  • Internal Server Error.
  • Is this you?
  • Claim your free profile.
  • Email
  • Home Phone
  • Work Phone
  • Cell Phone
  • Contact Form
  • Calendar

The i18n option is an object that maps from the English text to the language of your choice (even another English phrase, if you wish to change the text).

Translations are treated as plain text: any HTML in them is escaped rather than rendered. Pass unescaped strings (for example, WordPress's __() rather than esc_html__()), or entities such as &#039; will be shown literally.

{
  'Edit your profile →': 'Modifier votre profil →'
}

Contribute to Gravatar Hovercards

We welcome contributions to this project. Please follow the guidelines outlined in the CONTRIBUTING.md file.

License

Gravatar Hovercards is licensed under GNU General Public License v2 (or later).

版本与发布记录

@gravatar-com/hovercards 共发布 41 个版本,首次发布于 2023/08/02;过去 12 个月发布了 2 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
0.17.0latest2026/10/3018 天前
0.16.02026/03/188 个月前
0.15.02025/08/261.2 年前
0.14.02025/06/301.4 年前
0.13.02025/05/011.5 年前
0.12.02025/04/231.6 年前

关于 @gravatar-com/hovercards 的常见问题

@gravatar-com/hovercards 是什么?

Add profile hovercards to Gravatar images.

如何安装 @gravatar-com/hovercards?

在项目目录运行 npm install @gravatar-com/hovercards,或使用 pnpm add / yarn add / bun add。

@gravatar-com/hovercards 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@gravatar-com/hovercards 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@gravatar-com/hovercards 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=20。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@gravatar-com/hovercards 可以商用吗?

@gravatar-com/hovercards 使用 GPL-2.0-or-later 许可。强 Copyleft:分发包含该代码的软件时,整个作品需以兼容的 GPL 许可开源。仅在内部使用、不对外分发时不触发此义务。以上为概括,不构成法律意见,请以许可原文为准。

@gravatar-com/hovercards 的下载量有多少?

根据 npm 官方下载统计,@gravatar-com/hovercards 在 2026/10/17 – 2026/11/15 这 30 天内被下载 5,247 次,日均约 175 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@gravatar-com/hovercards 还在维护吗?

最新版本 0.17.0 发布于 2026/10/30(18 天前);至今共发布 41 个版本,其中过去 12 个月发布了 2 个;首次发布于 2023/08/02。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。