Listen to an annotation’s hover event
The SDK doesn’t emit a native “hover” event for annotations. However, you can simulate this behavior using standard DOM event listeners. The following example detects hover events for most annotation types:
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"); } } ); });
For annotation types such as text, markup, and links, the method above doesn’t work because the annotation types use custom hit testing logic. To detect hover events on these annotation types, use the Custom Renderers API as demonstrated in the following code snippet:
let pspdfkitInstance; // Global or module-level variable. PSPDFKit.load({ ...baseOptions, toolbarItems: [ ...PSPDFKit.defaultToolbarItems, { type: "cloudy-rectangle", dropdownGroup: "shapes" }, { type: "dashed-rectangle", dropdownGroup: "shapes" }, { type: "cloudy-ellipse", dropdownGroup: "shapes" }, { type: "dashed-ellipse", dropdownGroup: "shapes" }, { type: "dashed-polygon", dropdownGroup: "shapes" }, { type: "content-editor", dropdownGroup: "editor" }, { type: "form-creator", dropdownGroup: "editor" }, { type: "measure", dropdownGroup: "editor" }, { type: "document-comparison", dropdownGroup: "editor" } ], customRenderers: { Annotation: ({ annotation }) => { if ( annotation instanceof PSPDFKit.Annotations.TextAnnotation || annotation instanceof PSPDFKit.Annotations.MarkupAnnotation || annotation instanceof PSPDFKit.Annotations.LinkAnnotation ) { const node = document.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) => { pspdfkitInstance = instance; // Assign instance to the global/module. variable 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"); } } ); });