Search code examples
javascripttwitter-bootstraptooltip

bootstrap tooltip: how to specify tooltip text using a javascript function


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
  }    

Solution

  • 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
    })