Problem/Motivation

Javascript debugger console shows Uncaught TypeError when running subtheme main.script.js from subtheme starter kit.

Steps to reproduce

1. Create subtheme.
2. Use tooltips in rendered output via data-bs-toggle="tooltip"
3. Ensure that the tooltip bootstrap library is not commented out and that the behavior code in main.script.js is uncommented.
4. Build the javascript with npm run watch
5. Load a page and observe the javascript console.

Proposed resolution

I don't know why, but at the time of the very first Drupal behavior attach invocation. the tooltip / popover / toast plug-in is not yet loaded. The context is the whole HTMLDocument. The next time attach is called, the plug-in is installed. This means that context cannot be used to narrow the search for the newly-added HTML elements.

This seemed to happen in radix 7.3 too. See related issue #2212123. However if you use that code, the tooltips will be repeated initialized, once for each call to attach after the first one.

My workaround is:

  // Enable Bootstrap Tooltips, Popover, and/or Toasts sitewide.
  // These are opt-in for performance reasons.
  Drupal.behaviors.bsPopover = {
    attach: function (context) {
      // Tricky bit here. The first time this behavior is attached, the context
      // is the entire HTML document. However, the tooltip plug-in has not yet
      // been installed (for some reason, not sure why). An attempt to find the
      // elements that need a tooltip and install it will result in a javascript
      // Uncaught TypeError. However, additional elements are attached and by
      // then the plug-in is present. However that means context cannot be used.
      if ($.fn.tooltip) {
        $('[data-bs-toggle="tooltip"]').once('deradix-tooltip').tooltip();
      }


      // $('[data-bs-toggle="popover"]').popover();
      // $('.toast').toast('show');
    }
  };

However, the correct implementation would be to figure out why (at least in my case) the plug-in isn't loaded before the first behavior attach call is made.

Remaining tasks

Comments

DanChadwick created an issue. See original summary.

danchadwick’s picture

Note that #1 uses jQuery.once, which is being phased out. Depending upon your situation, you might need to depend upon library the core jquery once library or re-write without jQuery and depend upon the standalone non-jquery once library.

doxigo’s picture

Status: Active » Fixed

Hey Dan, thanks for bringing this up, I ended up changing the `import` to a named module `export` for those modules that need initiation such as Tooltip & Toast

Check the latest dev and it should be good, will release a new RC soon

Status: Fixed » Closed (fixed)

Automatically closed - issue fixed for 2 weeks with no activity.