Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery UI Tooltip: Close on click on tooltip itself

I have a page with a jQuery UI tooltip that is initially opened and its closing on mouseout event is disabled.

Now, I want the tooltip to close after a user clicks on it itself, not on the element for which the tooltip is shown (as many other answers here).

As one of the possible solutions, I thought I can add a click handler to the tooltip's div and close it from there. But I can't find a standard way to obtain the tooltip's div with the Tooltip widget API or attach the handler in some other way.

Am I on the right track with the approach above? Or how to achieve what I am after in a different way?

JSFiddle illustrating what I have for the moment.

like image 797
Alexander Abakumov Avatar asked May 06 '16 16:05

Alexander Abakumov


2 Answers

I've found a relatively simple solution without hacking the Tooltip API via attaching a click handler in the tooltip's open event and closing the tooltip there:

$('.first')
    .tooltip({
         content: 'Click to close',
         position: { my: 'left center', at: 'right center' },
         items: '*'

         open: function (event, ui) {
             var $element = $(event.target);
             ui.tooltip.click(function () {
                 $element.tooltip('close');
             });
         },
    })
    .tooltip('open')
    .on('mouseout focusout', function(event) {
        event.stopImmediatePropagation();
    });

JSFiddle

like image 82
Alexander Abakumov Avatar answered Oct 03 '22 01:10

Alexander Abakumov


Try this:

$(document).ready(function(){
    $('.first')
        .tooltip({ content: 'Click to close', position: { my: 'left center', at: 'right center' }, items: '*' })
        .tooltip('open')
        .on('mouseout focusout', function(event) {
            event.stopImmediatePropagation();
        })

        // when the tooltip opens (you could also use 'tooltipcreate'), grab some properties and bind a 'click' event handler
        .on('tooltipopen', function(e) {
            var self = this, // this refers to the element that the tooltip is attached to
                $tooltip = $('#' + this.getAttribute('aria-describedby')); // we can get a reference to the tooltip via the `aria-describedby` attribute

            // bind a click handler to close the tooltip
            $tooltip.on('click', function() {
                $(self).tooltip('close');
            });
        });
}); 
  • Updated JSFiddle
  • jQuery UI Tooltip API
like image 34
André Dion Avatar answered Oct 02 '22 23:10

André Dion