2

I'm using Twitter Bootstrap to create tooltips. Currently, I init the tooltips in $(document).ready():

$(document).ready(function() {
    $('[data-toggle="tooltip"]').tooltip();
});

This calls tooltip() (which inits the listeners) for every element that has the data-toggle element.

The problem is that if I have dynamic DOM elements (using Ajax), the tooltip() will not be called on them. I thought of a solution like the following:

$(document).ready(function() {
    $('body').on('ready', '[data-toggle="tooltip"]', function() {
        $(this).tooltip();
    });
});

But that doesn't work..

Any ideas..?

tamir
  • 3,207
  • 2
  • 33
  • 51
  • What bout just executing `$('[data-toggle="tooltip"]').tooltip();` when new items are added? – Lix Oct 25 '12 at 12:21
  • 1
    Try to not use data as selectors. They are not meant for that, and they are slow to select. Use classes or ID instead. Also, if you set data attributes with `.data()`, your selectors won't work. http://stackoverflow.com/questions/2891452/jquery-data-selector – Maktouch Oct 25 '12 at 12:43

1 Answers1

5

Just re-init the plugin once your ajax method has returned (and the new elements have been injected):

$.ajax({
    url: 'foo.html',
    type: 'post',
    data: { foo: "bar"},
    success: function (html) {

        $("#foo").html(html);
        $('[data-toggle="tooltip"]').tooltip();
    }
});
karim79
  • 339,989
  • 67
  • 413
  • 406