Listen to an Annotation’s Hover Event

You may want to listen to a text annotation’s “hover” event, however, these aren’t emitted. That said, it’s possible to achieve something similar to listening to a hover event. For most annotation types, the following snippet works:

PSPDFKit.load(defaultConfiguration).then((instance) => {
  instance.contentDocument.addEventListener(
    "mouseover",
    ({ target }) => {
      if (
        target &&
        (target.closest(".PSPDFKit-Annotation") ||
          target.classList.contains("PSPDFKit-Annotation"))
      ) {
        // The annotation ID can be obtained from the `data-annotation-id` attribute of
        // the closest `.PSPDFKit-Annotation` element.
        console.log("Annotation hovered");
      }
    }
  );
});

However, some annotation types (text, markup, and links) use custom hit testing logic that prevents getting the “hover” event this way. Instead, you can use the Custom Renderers API to achieve the same result. Putting both together results in the following snippet:

PSPDFKit.load({
  ...defaultConfiguration,
  customRenderers: {
    Annotation: ({ annotation }) => {
      if (
        annotation instanceof PSPDFKit.Annotations.TextAnnotation ||
        annotation instanceof PSPDFKit.Annotations.MarkupAnnotation ||
        annotation instanceof PSPDFKit.Annotations.LinkAnnotation
      ) {
        const node = instance.contentDocument.createElement("div");
        node.style.cssText =
          "position: absolute; width: 100%; height: 100%; pointer-events: all";
        const mouseoverListener = function () {
          console.log(
            `Hovered text annotation with ID: ${annotation.id}`
          );
        };
        node.addEventListener("mouseover", mouseoverListener);
        return {
          node,
          append: true
        };
      }
    }
  }
}).then((instance) => {
  instance.contentDocument.addEventListener(
    "mouseover",
    ({ target }) => {
      if (
        target &&
        (target.closest(".PSPDFKit-Annotation") ||
          target.classList.contains("PSPDFKit-Annotation"))
      ) {
        // The annotation ID can be obtained from the `data-annotation-id` attribute of
        // the closest `.PSPDFKit-Annotation` element.
        console.log("Annotation hovered");
      }
    }
  );
});

This has been tested with PSPDFKit for Web 2019.4.1