A common example: Bootstrap Tooltips

Imagine a list with a tooltip. As soon as we loaded the page, all the tooltips in this list are working. Oh yeah, we also have a file with this code in the <head> page:

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

Now add a duplicate element to this list using Ajax. No matter how exactly the Ajax request is implemented - the total is one.

The new item will not work tooltip. I correct the situation as follows: along with the html code (in this example, the html code of the list item), I also send this:

 <script>$('[data-toggle="tooltip"]').tooltip();</script> 

Added 10 items to the list, gathered 10 identical script lines under it. But everything works.

But there was a need to implement the functionality is not just a list. Now I have a lot of components on the page, each of which works on Ajax - pagination, the same list with elements, in which there is something else with Ajax. All that stuff.

And “curing” it the way I described it above is impossible.

Is there really no normal way for the "new elements from ajax" to interact with the JS environment of the page?

  • one
    Why send <script>$('[data-toggle="tooltip"]').tooltip();</script> markup if you can call this function yourself immediately after receiving it directly? - Grundy
  • one
    Congratulations, now you know why experienced developers hate "magic" jquery plugins. - Pavel Mayorov
  • @PavelMayorov, by the way, like, in jquery-ui Do not need to initialize each time - Grundy
  • @Grundy any dynamically created element needs to be initialized - Pavel Mayorov
  • one
    @Colibri Complete the question with a piece of code where you "tried to initialize after append" . Obviously, the answer lies there. - Alexander Igorevich

1 answer 1

 $('body').tooltip({ selector: '[data-toggle="tooltip"]' }); 

According to the documentation will work for dynamically added items.

  • Thank you very much! Since you have grasped the essence and your answer is correct, help (I beg you) with this question. I know, maybe arrogance, but the situation is more complicated. Same problem, only with intercoolerjs.org . I do not know how to initialize the library here after Ajax. The problem is that there is Ajax pagination. And when you go to a new page, Intercooler stops working completely. - Colibri
  • Created a separate question: ru.stackoverflow.com/questions/626122/… - Colibri