4

bootstrap tooltip allows me to specify tooltip for the element by merely specifying the "title" attribute:

<div title="This is a test tooltip"> ... </div>

Is there any way to avoid hardcoding the tooltip content and specify a javascript function instead? I tried title="javascript:myFunction()" but it doesn't resolve it.

I looked at the booststrap code and it seems to contain support for function call I just can't figure out the syntax:

Snippet from bootstrap tooltip:

, getTitle: function () { 
      var title
      , $e = this.$element
      , o = this.options

      title = $e.attr('data-original-title')
       || (typeof o.title == 'function' ? o.title.call($e[0]) :  o.title)

     return title
  }    

3 Answers 3

6

http://twitter.github.io/bootstrap/javascript.html#tooltips

Give your div an id and call

function titleSetter(node) {
   return "My Tooltip text";
}
$('#my-div-id').tooltip({
    title: 'My Tooltip text'
});

// or

$('#my-div-id').tooltip({
    title: titleSetter
})
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks. Got a bonus question though. If I use title="...." in html source then the tooltop is displayed in white font on black background. When I use he tooltip() function as in your method the tip is displayed in dark font on yellow-ish background. How can I control the tooltip display theme?
@Ya. Sorry, you should ask a new question, that way, it will be easy for other users to find it. But I'm sure it's pretty easy to control with CSSS
upvoted how do you call tooltip function without jquery?
@PirateApp Set it in the HTML? If you want it dynamic, you need the jQuery plugin.
1

I dont know how to use a function, but I use a config file to hold the title/body of my tooltips. I then use a data-attribute for the title and body and leave it in my html. Here is my config file (really just some json):

var help = {
    '001': {
      title: 'Title 1',
      description: 'Body 1'
    },
    '002': {
      title: 'Title 2',
      description: 'Body 2'
    }
  }

My html looks just like it sounds:

  <div data-help="001"></div>

I then make the title and content return a function in my tool tips, like so:

var tooltipOptions = {
    trigger: 'manual',
    title: function() {
      return help[$(this).attr('data-help')].title;
    },
    content: function() {
      return help[$(this).attr('data-help')].description;
    }
  };

And I now have a dynamic body and title for my tool tips.

I believe this will solve the problem you were encountering in your question. Good luck!

Comments

1

if you are using bootstrap 3, you can put a id in your div

<div id="title-text" title="This is a test tooltip"> ... </div>

and then use this code

$("#title-text").attr('data-original-title', "the title");

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.