Search code examples
javascriptjqueryhtmljquery-uitooltip

Hiding jQueryUI tooltip when clicking on target="_blank" link


I'm using jQuery to show tooltips on every link on my page that has a 'details' attribute

        $(function() {
            $tooltip = $(document).tooltip({
                show: false,
                track: true,
                items: "a[data-details]",
                content: function() {
                    return $( this ).data('details');
                }
            });
        });

This works very well. However, when the user clicks one of those links, the URL is opened in a new tab (using target="_blank"). The problem is that the tooltip is still open when the user gets back on the first tab.

Here's what I tried so far:

$('a[data-details]').on('click mousedown mouseup', function() { // this might be overkill
    $(document).tooltip("close");                               // Doesn't work at all
    $('div[class^="ui-tooltip"]').remove();                     // removes the tooltip onclick, but gets it back opened when returning on the tab
});

Is there a way to keep the tooltips closed when the new page is opened?

Thank you for your help.

Here's a fiddle illustrating the problem: https://jsfiddle.net/su4v757a/

Note: I'm using jQuery 1.12.4 with jQueryUI 1.12.1


Solution

  • This is probably a bug.

    As far as I can tell this must be a bug. And you could let them know over at https://bugs.jqueryui.com/report/10?P=tooltip

    I notice that the .tooltip("close") doesn't work in the fiddle. However the tooltip listens to the "mouseleave"-event to close, and we can force that by $('a[data-details]').trigger("mouseleave");

    If you try this out you will see that it do close, but pops up again:

    $('a[data-details]').on('click mousedown mouseup', function() { // this might be overkill
        $(this).trigger("mouseleave");
      });
    

    Hover and click the "me":

    Hover and click the "me"

    Coming back to the page notice that the tooltip has closed and come back again: enter image description here

    Workaround - possible solution

    Since .hide()-ing an element triggers the "mouseleave"-event you could do something funky like hiding the link on click, and showing it just a moment later.

      $('a[data-details]').click(function() {
        var $this = $(this);
        $this.hide(); 
        setTimeout(function() {
          $this.show()
        }, 1);
      });
    

    Setting the timeout to 1 ms would not create any flickering of the link, making the hide/show unnoticeable for the user.

    Works in Chrome. Try it here: https://jsfiddle.net/cyx6528e/1/ Good luck!