how to close jQuery tooltip

Kristian picture Kristian · Aug 7, 2012 · Viewed 14.6k times · Source

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.

Answer

Declan McNulty picture Declan McNulty · Aug 7, 2012

To close a tooltip you need to call

$('.tooltip').remove();

In your scenario try

$.each($('.tooltip'), function (index, element) {
    $(this).remove();
 });