7

I'm attempting to use HTML5 data attributes to store and display content for a tooltip.

I'm using JQuery UI for the tooltip.

I've read the documentation, but haven't figured out how to program the right selector and display the custom data.

Any ideas of what I'm missing?

http://jsfiddle.net/QsEJk/2/

HTML:

<span class="info-icon"
    data-title="custom title"
    data-desc="custom description">
</span>

JS:

$( '.info-icon' ).tooltip({
    content: function() {
        return 'Title: ' + $( this ).data('title') +
               ' Description: ' + $( this ).data('desc');
    }
});
4
  • First, you should write ready(function() { instead of ready({. Second, you should add your jQuery UI theme's CSS file as an external resource to your fiddle (and maybe in your page also). The rest of the code looks fine. Commented Jul 5, 2013 at 19:20
  • Whoops, I just omitted it since fiddle takes care of that. Commented Jul 5, 2013 at 19:28
  • Well, nope. jsFiddle handles the inclusion of the jQuery UI scripts, but not of its CSS files. Commented Jul 5, 2013 at 19:30
  • Made changes and no dice. Commented Jul 5, 2013 at 19:30

2 Answers 2

11

You need the items option

$(".info-icon").tooltip({
    items: "[data-title], [data-desc]",
    content: function () {
        return 'Title: ' + $(this).data("title") + ' Description: ' + $(this).data('desc');
    }
});

http://api.jqueryui.com/tooltip/

Edit:

[data-title],[data-desc] will work if either attribute is on the .info-icon span.

[data-title][data-desc] will require both attributes specified for the tooltip to work.

Sign up to request clarification or add additional context in comments.

4 Comments

Or maybe [data-title][data-desc] since the content function uses both attributes?
Hmm, the items option makes the API a bit confusing, but thank you!
Why do you need the function&return to specify the content? Why doesn't "content: $(this).data('text')" this work? Can you please explain? Thank you!
@lehel content is a callback delegate function. The plug-in expects to run content as a function.
2

The accepted answer worked for me but in my case I wanted this applied to many items on the page so didn't want a variable for every one. Instead I used this:

        $(".help").each(function() {
            $(this).tooltip({
                content: $(this).data('help')
            });
        });

This applies the data-help content to every .help item on the page.

1 Comment

It works on multiple items by default.Please see this fiddle: jsfiddle.net/QsEJk/21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.