MutationObserver

Example

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
// REMOVE TRAILING SPACE FOR AUTO COMPLETE ON PUBLICATION AND SPEECHES
    function addEventListener_removeAutoCompleteNumber(input_selector) {
      const removeTrailingNumberPattern = (str) => str.replace(/\s*\(\d+\)$/, '');

      const attachHandlers = (input) => {
          const updateValue = () => {
              setTimeout(() => {
                  input.value = removeTrailingNumberPattern(input.value);
              }, 0);
          };

          // Handle focusout for manual cleanup
          input.addEventListener('focusout', () => {
              input.value = removeTrailingNumberPattern(input.value);
          });

          // Handle dynamic autocomplete menu updates
          const observer = new MutationObserver((mutations) => {
              mutations.forEach((mutation) => {
                  if (mutation.addedNodes.length) {
                      document.querySelectorAll("ul.ui-menu.ui-autocomplete > li > a.ui-menu-item-wrapper").forEach((item) => {
                          item.onclick = () => updateValue();
                      });
                  }
              });
          });

          // Observe the autocomplete menu for changes
          const autocompleteMenu = document.querySelector(".ui-menu.ui-autocomplete");
          if (autocompleteMenu) {
              observer.observe(autocompleteMenu, { childList: true });
          }
      };

      // Attach handlers to all matching inputs
      document.querySelectorAll(input_selector).forEach((input) => {
          input.addEventListener('input', () => {
              setTimeout(() => attachHandlers(input), 500);
          });
      });
    }

    // Initialize on DOM load
    document.addEventListener('DOMContentLoaded', () => {
      addEventListener_removeAutoCompleteNumber(".path-news input[data-once='autocomplete']");
      addEventListener_removeAutoCompleteNumber(".path-speeches input[data-once='autocomplete']");
      addEventListener_removeAutoCompleteNumber(".path-publications input[data-once='autocomplete']");
    });