Question

I have a administration website that uses icons to indicate when something can be deleted, edited or created. I use bootstraps tooltip to do that, and binding a tooltip to all elements on every page that has delete icons/buttons is easy:

$('.delete-btn').tooltip({
  placement: 'top',
  title: 'Slet'
});

Since I use ajax and dom manipulation to add new elements (new delete buttons), the previous example will not add tooltip to newly (after document ready) added buttons. I found a solution like this:

$('body').tooltip({
    selector: '.delete-btn',
    placement: 'top',
    title: 'Slet'
});

That works as well. The problem is that i need tooltips on '.edit-btn' as well. I figured i could just replicate the above example and change the selector to '.edit-btn'. The thing is - it doesn't work - only the first tooltip on the body element seems to work. I tried swapping the order and then i can get '.edit-btn' to work, but then '.delete-btn' stops working. It seems only only tooltip can be set on a given element (body) at a time, and only the first one works - even when i pass different selectors?

Am I missing something here - is there an easy solution to this? I would really love if i don't have to manually initialize every newly created element with a tooltip manually. I was also thinking of doing a

$('body').on('mouseover', '.btn-delete', function()...
$('body').on('mouseout', '.btn-delete', ....

But that seems like a lot of work and moves the responsibility of showing the tooltips away from bootstraps plugin and into my own code...

Was it helpful?

Solution

I think i found the solution, but I'll leave it here so you can tell me if there is a better way.

$('body').tooltip({
    selector: '.edit-btn, .delete-btn, .create-btn',
    placement: 'top',
    title: function () {
        var elem = $(this);
        if (elem.hasClass('edit-btn'))
            return 'Rédiger';
        if (elem.hasClass('delete-btn'))
            return 'Slet';
        if (elem.hasClass('create-btn'))
            return 'Opret';

        return 'fejl match tooltip';
    }
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top