Question

I've been searching the Internet and it's tough to find solutions that don't rely on third-party plugins.

I found a few:

But none of them, as far as I've been able to tell, support the creation of these tooltips when the elements are not loaded beforehand. So, if we load an element via AJAX, the tooltips won't work.

So, I came up with a very simple solution - maybe not the best, but works for me - that relies only on jQuery functions without third-party plugins. See below.

Was it helpful?

Solution

What I basically do is first initiate the tooltip jQuery function, as they do in their documentation:

$(document).ready(function(){
    $(document).tooltip({
        items: ".info_warning",
        content: function () {
                var element = $(this);
                if (element.is(".info_warning")) {
                    return element.text()
                }
            }, 
            tooltipClass: "info_tooltip"
        })
    })

As you can see, I tell it to look only for those elements with the class "info_warning" and that its content is the element content (this is because I prefer not to rely in title attribute).

Then, what I do is to tell it that if a "click" or a "touch" event is detected, check for the attribute "aria-describedby", that is an attribute that jQuery adds to the element whenever a tooltip from it is being shown (so, this way I know if the tooltip is active or not).

Finally, if the tooltip is not active, I trigger a "mouseover" event to simulate the hover effect by the mouse, and if it's active I trigger a "mouseleave".

$(document).on("click touchend", ".info_warning", function(){
    if($(this).attr("aria-describedby") === undefined) $(this).trigger("mouseover")
    else $(this).trigger("mouseleave")
})

I've written both events ("click" and "touchend") because it's not important, as it will only make disappear the tooltip in case it's already activated, but it would be only necessary the "touchend" event.

Hope it helps to somebody!

Kind regards.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top