javascriptjqueryjquery-tooltip

how to close jQuery tooltip


I've been trying to make very simple javascript tooltip with jQuery but I've hit a brick wall. The idea is to have little inline element (span) inside a div. The span element will contain a tooltip div with a little html (image and link). Tooltip should be opened when clicked on the span element and closed when clicked outside of it or outside of the tooltip.

So far, opening the tooltip is not a problem but closing is.

<!DOCTYPE HTML>
<html>
<head>
    <title></title>

    <style>
        #colors > div {
            background-color: red;
            height: 50px;
            width: 50px;
            margin: 5px;
        }

        #colors > div > span {
            min-height: 10px !important;
            min-width: 10px !important;
            border: 3px solid black;
            position: relative;
        }

        .tooltip {
            border: 2px solid blue;
            display: none;
        }
    </style>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
    <script>
        $(function () {
            // generate boxes and tooltips
            for (var i = 0; i < 9; i++) {
                $('#colors').append('<div id="' + i + '"><span><div class="tooltip"><a href="#">add to favorites</a></div></span></div>');
            }

            $('#colors').delegate('span', 'click', function (event) {
                $(this).children('.tooltip').css({position:'absolute', top:'5px', left:'5px'}).fadeIn();
                // bottom one won't work
                //event.stopPropagation();
            });

            $(document).delegate('body', 'click', function (event) {
                var that = this
                $.each($('.tooltip'), function (index, element) {
                    // it's always visible ...
                    //if ($(element).is(':visible')) {

                    // doesn't work either
                    if ($(element).is(':visible') && $(element).has(event.target).length === 0) {
                        var s = event.target;

                        console.log([($(s) == event.target), event.target, index, element, $(element).has(event.target).length, that]);
                    }
                });
            });
        })
    </script>
</head>
<body>
<div id="colors"></div>
</body>
</html>

I can't seem to find a way to close the tooltip if click is outside of the span and tooltip.


Solution

  • Something like this should work fine :)

     $(document).mouseup(function (e)
     {
         var container = $("YOUR CONTAINER SELECTOR");
    
         if (container.has(e.target).length === 0)
         {
            container.hide();
         }
     });