Search code examples
javascriptjquerytooltip

jQuery Blur() not working with click() function


I am trying to make a tooltip with content disappear when I click outside it, but tried solutions to different posts and none of those solutions work for me.

I think the problem is how I am triggering the tooltip, but is the only way I know, here is the code I have in my js and my html markup.

The tooltip fires well, but it doesn't work with the blur event in any way I tried.

$(document).ready(function() {

    function tooltover(target_item){
        $(target_item + '> a').click(function(){
            $('.tiptover_box').focus();

            var pos = $(this).position();
            var width = $(this).outerWidth();
            var boxw = $(this).next().outerWidth();
            var boxh = $(this).next().outerHeight();

            $(this).next().css('left', (pos.left - ((boxw/2)-(width/2))));
            $(this).next().css('top', (pos.top - (boxh+5)));
            $(this).next().addClass('tiptover_show');
            $(this).next().delay(5).queue(function(){
                $(this).addClass('tt-in');
                $(this).dequeue();
            });
        });
        $('.tiptover_box').blur( function(){
            $('.tiptover_box').removeClass('tiptover_show tt-in');
        });
    } tooltover('.tiptover');

});

And HTML

<div class="tiptover">
    <a>Link Test</a>
    <div class="tiptover_box" style="background-image: url(content/prod_0002.jpg);">
        <div>Description.</div>
    </div>
</div>

Solution

  • A different approach would be to not focus on the div itself, but focus on the rest of the DOM.

    In this solution given by prc322 on a similar question he used the mouseup event on the document itself:

    $(document).mouseup(function (e)
    {
        var container = $(".tiptover_box");
    
        if (!container.is(e.target) // if the target of the click isn't the container...
            && container.has(e.target).length === 0) // ... nor a descendant of the container
        {
            container.removeClass('tiptover_show tt-in');
        }
    });
    

    (edited by me for relevance)

    Now your tooltip will be "closed" whenever a mouseup event fired on any element that is not the .tiptover_box or any of its descendants.