Add listener to a default toolbar item

Q: How can I add a custom event listener to a DOM element that is part of a default toolbar item?

A: You can use one of the public CSS classes as a selector for adding the event listener you need, e.g. for click events.

Let’s imagine the scenario where we want to handle clicks performed on the input that indicates the current page, that is part of the pager toolbar item. That particular inputs gets re-rendered every time the current page changes, so we need to add a listener to viewState.currentPageIndex.change events on the PSPDFKit for Web instance to reattach the listeners:

Copy
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
let instance = null;

PSPDFKit.load({
  // your configuration
}).then(instance => {
  function attachListener() {
    instance.contentDocument
      .querySelector(".PSPDFKit-Page-Indicator-Input")
      .addEventListener("click", () => {
        console.log("Click!");
      });
  }

  attachListener();

  instance.addEventListener("viewState.currentPageIndex.change", e => {
    // Wrap on setTimeout to wait for next event loop run
    setTimeout(() => {
      attachListener();
    });
  });
});

This has been tested with PSPDFKit for Web 2019.5.4.