Bootstrap 3 tooltip event delegation attaching to individual elements

30 views Asked by At

I am optimizing out frontend with heavy technical debt (jQuery, Bootstrap 3... I know, not up to me) and now comes the turn of tooltips. This page in particular has several hundred elements using tooltips which are initialized the usual way:

$('[data-toggle="tooltip"]').tooltip()

This of course targets individual elements resulting in hundreds of listeners being attached and contributing negatively to performance.

I am using a mix of the selector option to attach tooltips to a single common parent and this technique to be able to initialize tooltips to that same parent multiple times (i.e. tooltips being initialized in different parts of the code with different options):

/**
 * Attaches a tooltip to the given jQuery element using event delegation. This technique allows attaching
 * multiple tooltips to the same element with different selectors.
 * @param {jQuery} $el - The jQuery element to attach the tooltip listeners to.
 * @param {Object} options - Bootstrap tooltip options.
 * @returns {jQuery} The jQuery object for chaining.
 */
function attachTooltip($el, options = {}) {
    const defaultOptions = {
        title: function () {
            return $(this).attr('title') || $(this).data('title') || '';
        }
    };
    return new $.fn.tooltip.Constructor($el, {...defaultOptions, ...options});
}

I thought this would be good enough (until being able to modernize our code, of couse) but upon inspecting targeted elements with the browser tools, I found out the related event listeners (focusin, focusout, mouseout, mouseover) are still being attached to each individual element matching the selector.

attachTooltip($('body'), {
    selector: '.ttooltip'
});

I would have expected 4 listeners attached to body and Bootstrap to handle the selector matching internally, instead of falling back to individual even listeners.

Any insights? Did I get it wrong, or this is by design? Do up-to-date Bootstrap versions handle it as I would expect? Can I hack in the expected behavior somehow, maybe even wrapping a different tooltip library that does behave this way?

0

There are 0 answers