最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - how to close jQuery tooltip - Stack Overflow

programmeradmin9浏览0评论

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=".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.

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./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.

Share Improve this question edited Sep 26, 2018 at 9:39 Luuklag 3,91412 gold badges39 silver badges59 bronze badges asked Aug 7, 2012 at 7:06 KristianKristian 1,0971 gold badge11 silver badges16 bronze badges 1
  • 1 Editing your question is not the correct way to let people know your problem is solved. Accepting an answer would be the correct way. If you solved your problem in a different way then the current answers please provide an answer yourself. – Luuklag Commented Sep 26, 2018 at 9:40
Add a ment  | 

5 Answers 5

Reset to default 6

To close a tooltip you need to call

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

In your scenario try

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

Something like this should work fine :)

 $(document).mouseup(function (e)
 {
     var container = $("YOUR CONTAINER SELECTOR");

     if (container.has(e.target).length === 0)
     {
        container.hide();
     }
 });

I investigated this issue for my own site and didn't find any suitable solution, so I wrote my own. My use case is a bit different to the OPs, but might help other people searching for the same term. I needed a close link that only appears on mobile platforms. This is useful because on a desktop, the tool tip will close when you mouseout from the target element, but on a touch platform it sticks around.

// Set up tool tips for images and anchors.
$( document ).tooltip({
  items: "a[title], img[alt], .toolTip[title], :not(.noToolTip)",
    track: true,
    position: { my: "left+15 center", at: "right center" },
   content: function() {
      var element = $( this );
      var closer = closerLink = '';
      if (isMobile()) {
         closer = ' <br><div onClick="$(this).parent().parent().remove();" style="color: blue; text-decoration: underline; text-align: right;">Close</div>';
         closerLink = ' <br>Tap link again to open it.<br><div onClick="$(this).parent().parent().remove();" style="color: blue; text-decoration: underline; text-align: right;">Close</div>';
      }
      // noToolTip means NO TOOL TIP.
      if ( element.is( ".noToolTip" ) ) {
         return null;
      }
      // Anchor - use title.
      if ( element.is( "a[title]" ) ) {
         return element.attr( "title" ) + closerLink;
      }
      // Image - use alt.
      if ( element.is( "img[alt]" ) ) {
         return element.attr( "alt" ) + closer;
      }
      // Any element with toolTip class - use title.
      if ( element.is( ".toolTip[title]" ) ) {
         return element.attr( "title" ) + closer;
      }
   }
});

function isMobile() {
   return (/iPhone|iPod|iPad|Android|BlackBerry/).test(navigator.userAgent);
}

I am targeting three types of things here:

  • Anchor tags (a) with a title attribute.
  • Image tags (img) with a title attribute.
  • Any element with class toolTip.
  • And specifically exclude any element with class noToolTip.

I wrote this up here: JQuery UI tooltip with a close link for mobile

When you generate the tooltips, save the result to a variable. You can use it after to close all the tooltips.

var tooltips = $(document).tooltip({
    // all kind of initilization options like position, open, hide, etc.
});

// ... app logic ...

tooltips.tooltip('close') // will close all tooltips

had the info from here: https://jqueryui./tooltip/#forms

 $(document).mouseup(function (kamesh)
 {
     var container = $("YOUR CONTAINER SELECTOR");

     if (container.has(kamesh.target).length === 0)
     {
        container.hide();
     }
 });
发布评论

评论列表(0)

  1. 暂无评论