89

Today, I upgraded all of my jQuery plugs-in with jQuery 1.9.1. And I started to use jQueryUI tooltip with jquery.ui.1.10.2. Everything was good. But when I used HTML tags in the content (in the title attribute of the element I was applying the tooltip to), I noticed that HTML is not supported.

This is screenshot of my tooltip:

enter image description here

How can I make HTML content work with jQueryUI tooltip in 1.10.2?

Andrew Whitaker
  • 124,656
  • 32
  • 289
  • 307
  • 1
    Is this something that just broke since you upgraded? It seems to work fine for me in jQuery 1.9.1, jQuery UI 1.9.2 http://jsfiddle.net/2n3DL/1/ – metadept Mar 31 '13 at 20:35
  • Hımm.It is good idea. Can I ask one more question if you let me. Ok, I have a tooltip icon and it has got a class named as "tooltip" like this: How can I use like this? Best regards. –  Mar 31 '13 at 20:52
  • see metadepts updated fiddle with jquery ui 1.10.2 [here](http://jsfiddle.net/JmBPN/1/) and jquery 1.9.1. It still works. – SachinGutte Mar 31 '13 at 20:53
  • @phobos: No, it doesn't. There are `` tags right in the tooltip. – Andrew Whitaker Mar 31 '13 at 20:53
  • in demo i mentioned in comment ? – SachinGutte Mar 31 '13 at 20:55
  • 1
    Hover over "Some input" (The tooltip directly returning HTML content works fine). I know the OP's question is kind of unclear, but I'm assuming he or she is using HTML in the `title` attribute, which is unsupported as of 1.10. – Andrew Whitaker Mar 31 '13 at 20:56
  • @Andrew Whitaker said great. My question may be not clear enough. Because English is not my native language. Yes, I am using HTML in the title attribute. And now, I tested it. When I downgrade jquery.ui 1.9.2 it worked fine. So I understood that using HTML in the title attribute does not supported by the version of 1.10.2. Thanks so much to everyone who answered. –  Mar 31 '13 at 21:20

15 Answers15

198

Edit: Since this turned out to be a popular answer, I'm adding the disclaimer that @crush mentioned in a comment below. If you use this work around, be aware that you're opening yourself up for an XSS vulnerability. Only use this solution if you know what you're doing and can be certain of the HTML content in the attribute.


The easiest way to do this is to supply a function to the content option that overrides the default behavior:

$(function () {
      $(document).tooltip({
          content: function () {
              return $(this).prop('title');
          }
      });
  });

Example: http://jsfiddle.net/Aa5nK/12/

Another option would be to override the tooltip widget with your own that changes the content option:

$.widget("ui.tooltip", $.ui.tooltip, {
    options: {
        content: function () {
            return $(this).prop('title');
        }
    }
});

Now, every time you call .tooltip, HTML content will be returned.

Example: http://jsfiddle.net/Aa5nK/14/

Community
  • 1
  • 1
Andrew Whitaker
  • 124,656
  • 32
  • 289
  • 307
  • 4
    The only problem with this is it circumvents the very reason that jQuery started escaping HTML in the title attribute to begin with. – crush Jul 22 '13 at 21:18
  • 4
    @eidylon [`Putting HTML within the title attribute is not valid HTML and we are now escaping it to prevent XSS vulnerabilities`](http://bugs.jqueryui.com/ticket/9019#comment:2). In Andrew's answer, the title still has to contain HTML, which is invalid. – crush Oct 24 '13 at 20:05
  • You could have the text part of the content in the title attribute and then build the surrounding bits of HTML in your content callback to get around this (as long as you knew what it would be at init time) – jinglesthula Mar 05 '14 at 21:32
  • This answer has many upvotes. But I find Minh's answer [ https://stackoverflow.com/a/28941759/1063730 ] more on point. Referencing same ticket you do but using the content option instead of pushing fullblown html in the title-tag. – nuala Mar 09 '21 at 09:28
20

Instead of this:

$(document).tooltip({
    content: function () {
        return $(this).prop('title');
    }
});

use this for better performance

$(selector).tooltip({
    content: function () {
        return this.getAttribute("title");
    },
});
Profesor08
  • 1,181
  • 1
  • 13
  • 20
14

I solved it with a custom data tag, because a title attribute is required anyway.

$("[data-tooltip]").each(function(i, e) {
    var tag = $(e);
    if (tag.is("[title]") === false) {
        tag.attr("title", "");
    }
});

$(document).tooltip({
    items: "[data-tooltip]",
    content: function () {
        return $(this).attr("data-tooltip");
    }
});

Like this it is html conform and the tooltips are only shown for wanted tags.

Chris
  • 141
  • 1
  • 2
6

You can also achieve this completely without jQueryUI by using CSS styles. See the snippet below:

div#Tooltip_Text_container {
  max-width: 25em;
  height: auto;
  display: inline;
  position: relative;
}

div#Tooltip_Text_container a {
  text-decoration: none;
  color: black;
  cursor: default;
  font-weight: normal;
}

div#Tooltip_Text_container a span.tooltips {
  visibility: hidden;
  opacity: 0;
  transition: visibility 0s linear 0.2s, opacity 0.2s linear;
  position: absolute;
  left: 10px;
  top: 18px;
  width: 30em;
  border: 1px solid #404040;
  padding: 0.2em 0.5em;
  cursor: default;
  line-height: 140%;
  font-size: 12px;
  font-family: 'Segoe UI';
  -moz-border-radius: 3px;
  -webkit-border-radius: 3px;
  border-radius: 3px;
  -moz-box-shadow: 7px 7px 5px -5px #666;
  -webkit-box-shadow: 7px 7px 5px -5px #666;
  box-shadow: 7px 7px 5px -5px #666;
  background: #E4E5F0  repeat-x;
}

div#Tooltip_Text_container:hover a span.tooltips {
  visibility: visible;
  opacity: 1;
  transition-delay: 0.2s;
}

div#Tooltip_Text_container img {
  left: -10px;
}

div#Tooltip_Text_container:hover a span.tooltips {
  visibility: visible;
  opacity: 1;
  transition-delay: 0.2s;
}
<div id="Tooltip_Text_container">
  <span><b>Tooltip headline</b></span>
  <a href="#">
    <span class="tooltips">
        <b>This is&nbsp;</b> a tooltip<br/>
        <b>This is&nbsp;</b> another tooltip<br/>
    </span>
  </a>
  <br/>Move the mousepointer to the tooltip headline above. 
</div>

The first span is for the displayed text, the second span for the hidden text, which is shown when you hover over it.

Matt
  • 25,467
  • 18
  • 120
  • 187
4

From http://bugs.jqueryui.com/ticket/9019

Putting HTML within the title attribute is not valid HTML and we are now escaping it to prevent XSS vulnerabilities (see #8861).

If you need HTML in your tooltips use the content option - http://api.jqueryui.com/tooltip/#option-content.

Try to use javascript to set html tooltips, see below

$( ".selector" ).tooltip({
   content: "Here is your HTML"
});
Hắc Huyền Minh
  • 1,025
  • 10
  • 13
  • maybe due to an outdated jQuery version but: I needed to add an empty title tag to the element `.selector` is referring to! – nuala Mar 09 '21 at 09:29
3

To expand on @Andrew Whitaker's answer above, you can convert your tooltip to html entities within the title tag so as to avoid putting raw html directly in your attributes:

$('div').tooltip({
    content: function () {
        return $(this).prop('title');
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<div class="tooltip" title="&lt;div&gt;check out these kool &lt;i&gt;italics&lt;/i&gt; and this &lt;span style=&quot;color:red&quot;&gt;red text&lt;/span&gt;&lt;/div&gt;">Hover Here</div>

More often than not, the tooltip is stored in a php variable anyway so you'd only need:

<div title="<?php echo htmlentities($tooltip); ?>">Hover Here</div>
2

To avoid placing HTML tags in the title attribute, another solution is to use markdown. For instance, you could use [br] to represent a line break, then perform a simple replace in the content function.

In title attribute:

"Sample Line 1[br][br]Sample Line 2"

In your content function:

content: function () {
    return $(this).attr('title').replace(/\[br\]/g,"<br />");
}
2

another solution will be to grab the text inside the title tag & then use .html() method of jQuery to construct the content of the tooltip.

$(function() {
  $(document).tooltip({
    position: {
      using: function(position, feedback) {
        $(this).css(position);
        var txt = $(this).text();
        $(this).html(txt);
        $("<div>")
          .addClass("arrow")
          .addClass(feedback.vertical)
          .addClass(feedback.horizontal)
          .appendTo(this);
      }
    }
  });
});

Example: http://jsfiddle.net/hamzeen/0qwxfgjo/

Hamzeen Hameem
  • 2,360
  • 1
  • 27
  • 28
1
$(function () {
         $.widget("ui.tooltip", $.ui.tooltip, {
             options: {
                 content: function () {
                     return $(this).prop('title');
                 }
             }
         });

         $('[rel=tooltip]').tooltip({
             position: {
                 my: "center bottom-20",
                 at: "center top",
                 using: function (position, feedback) {
                     $(this).css(position);
                     $("<div>")
                         .addClass("arrow")
                         .addClass(feedback.vertical)
                         .addClass(feedback.horizontal)
                         .appendTo(this);
                 }
             }
         });
     });

thanks for post and solution above.

I have updated the code little bit. Hope this might help you.

http://jsfiddle.net/pragneshkaria/Qv6L2/49/

Liam
  • 27,717
  • 28
  • 128
  • 190
Pragnesh Karia
  • 509
  • 2
  • 6
  • 14
1

As long as we're using jQuery (> v1.8), we can parse the incoming string with $.parseHTML().

$('.tooltip').tooltip({
    content: function () {
        var tooltipContent = $('<div />').html( $.parseHTML( $(this).attr('title') ) );
        return tooltipContent;
    },
}); 

We'll parse the incoming string's attribute for unpleasant things, then convert it back to jQuery-readable HTML. The beauty of this is that by the time it hits the parser the strings are already concatenates, so it doesn't matter if someone is trying to split the script tag into separate strings. If you're stuck using jQuery's tooltips, this appears to be a solid solution.

ghettosoak
  • 319
  • 2
  • 11
1

You may modify the source code 'jquery-ui.js' , find this default function for retrieving target element's title attribute content.

var tooltip = $.widget( "ui.tooltip", {
version: "1.11.4",
options: {
    content: function() {
        // support: IE<9, Opera in jQuery <1.7
        // .text() can't accept undefined, so coerce to a string
        var title = $( this ).attr( "title" ) || "";
        // Escape title, since we're going from an attribute to raw HTML
        return $( "<a>" ).text( title ).html();
    },

change it to

var tooltip = $.widget( "ui.tooltip", {
version: "1.11.4",
options: {
    content: function() {
        // support: IE<9, Opera in jQuery <1.7
        // .text() can't accept undefined, so coerce to a string
        if($(this).attr('ignoreHtml')==='false'){
            return $(this).prop("title");
        }
        var title = $( this ).attr( "title" ) || "";
        // Escape title, since we're going from an attribute to raw HTML
        return $( "<a>" ).text( title ).html();
    },

thus whenever you want to display html tips , just add an attribute ignoreHtml='false' on your target html element; like this <td title="<b>display content</b><br/>other" ignoreHtml='false'>display content</td>

Joker
  • 11
  • 1
1

None of the solutions above worked for me. This one works for me:

$(document).ready(function()
{
    $('body').tooltip({
        selector: '[data-toggle="tooltip"]',
        html: true
     });
});
Avión
  • 7,963
  • 11
  • 64
  • 105
0

Html Markup

Tool-tip Control with class ".why", and Tool-tip Content Area with class ".customTolltip"

$(function () {
                $('.why').attr('title', function () {
                    return $(this).next('.customTolltip').remove().html();
                });
                $(document).tooltip();
            });
Billu
  • 2,733
  • 26
  • 47
0

Replacing the \n or the escaped <br/> does the trick while keeping the rest of the HTML escaped:

$(document).tooltip({
    content: function() {
        var title = $(this).attr("title") || "";
        return $("<a>").text(title).html().replace(/&lt;br *\/?&gt;/, "<br/>");
    },
});
-1

add html = true to the tooltip options

$({selector}).tooltip({html: true});

Update
it's not relevant for jQuery ui tooltip property - it's true in bootstrap ui tooltip - my bad!

Phlip
  • 5,253
  • 5
  • 32
  • 48