Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do not close tooltip when input has focus after click

How can I make tooltip do not be closed if input has focus? It works when it gets focus with tab, but if I use mouse to focus on input, tooltip will be closed on mouseout even if input has focus.

I can do

$('input').tooltip().off("mouseover mouseout");

But this will dissable tooltip on hover and I just need to dissable mouseout when input has focus.

http://jsfiddle.net/3dX6d/2/
http://jsfiddle.net/3dX6d/3/

like image 618
Qiao Avatar asked Feb 16 '23 10:02

Qiao


2 Answers

Try this:

Working Example

$("input").tooltip({
    close: function (event, ui) { //when the tooltip is supposed to close 
        if ($('input').is(':focus')) { // check to see if input is focused 
            $('input').tooltip('open'); // if so stay open
        }
    }
});

New and Improved Method:

Better Working Example

$("input").tooltip({
    hide: {
        effect: 'explode'// added for visibility
    } 
}).mouseleave(function () { // on mouse leave
    if ($('input').is(':focus')) { // if input is focused 
        ui.tooltip.preventDefault(); //prevent the tooltip's default behavior
        $('input').tooltip('open'); // leave the tooltip open
    }
}).focusout(function () { // on focus out 
    $('input').tooltip('close'); // close the tooltip
});

API documentation:
:focus
event.preventDefault()
.focusout()
open method
close event

like image 94
apaul Avatar answered Feb 17 '23 22:02

apaul


Instead of adding all these other listeners, I looked into the actual and decided the most effective way is to just inherit the widget and add an extra flag

http://code.jquery.com/ui/1.10.3/jquery-ui.js

Here's a demo http://jsfiddle.net/3dX6d/7/

(function ($) {
    $.widget("custom.tooltipX", $.ui.tooltip, {
        options: {
            focusPreventClose: false
        },

        close: function (event, target, content) {
            if (this.options.focusPreventClose && $(this.element).is(":focus")) {
                // Don't call the parent's close() call but therefore have to add event on focus out
                this._on({ focusout:this.close });
            } else {
                this._superApply(arguments);
            }
        }
    });
}(jQuery));

$('input').tooltipX({
    focusPreventClose: true
});

Compared to the other solution, this doesn't require us to do more work with the extra open calls (which actually does several other calls within it). We simply prevent the tooltip to close when we have the focus on the element, as requested by original post.

like image 38
jltwoo Avatar answered Feb 17 '23 22:02

jltwoo