Search code examples
jqueryeventstooltip

Function which shows tooltip on error and hides it on keypress


I can't figure out how to create this simple function without bugs. I don't really care what tooltip plugin I use, I tried 4 of them and I was not succesful in this with any of them. I want it to just work properly. I need it for validation purposes, so when user makes mistake, it will let him know immediately what he does wrong. When I try to create it, it either:

  • doesn't show at all
  • shows just for a moment
  • shows once and never hides
  • shows once, hides once and never reappear again

I have trouble either with conflicting keydown/keypress, destroying tooltip etc.

My try with jquery plugin tooltipster:

HTML:

<input type="text" />

JS:

jQuery.fn.tooltipError =
function(error)
{
    return this.each(function(e)
    {
        var t = $(this);
        t.tooltipster({ content: error, toggle: 'custom'});
        $(window).on('keyup',function() {
            // t.tooltipster('hide');
            t.tooltipster('destroy');
        });
        t.tooltipster('show');
    });
};

$('input').keydown(function(e) {
    if (e.key == 'a')
    {
        $(this).tooltipError('Char "a" not allowed');
        e.preventDefault();
    }
});

jsfiddle: http://jsfiddle.net/o946zb2b/


Solution

  • You should make sure you're only showing the tooltip when it's not already shown and only destroying it if it exsits. You also should not fire the keyup event when the pressed key is the one that triggered the tooltip in the first place. This will handle it:

    jQuery.fn.tooltipError =
    function(error, isError)
    {
        return this.each(function(e)
        {
            var t = $(this);
            if (!isError && t.hasClass("tooltipstered"))
                t.tooltipster("destroy");
    
            if (isError && !t.hasClass("tooltipstered"))
            {
                t.tooltipster({ content: error, toggle: "custom"});
                t.tooltipster("show");
            }
        });
    };
    
    $("input").keydown(function(e) {
        if (e.key == "a")
            e.preventDefault();
        $(this).tooltipError('Char "a" not allowed', e.key == "a");
    });
    

    FIDDLE

    EDIT: Updated the answer to remove double check and fix Fiddle link. Also, no warnings like this:

    Tooltipster: one or more tooltips are already attached to this element: ignoring. Use the "multiple" option to attach more tooltips.
    

    will be logged in the console when typing the a multiple times in a row.

    EDIT 2: Updated the answer to destroy the tooltip in the function itself.