0

When I load my page initially, I select everything using a certain CSS class, and then attach a tooltip to it as follows ("doTooltip" is the name of the CSS class):

$(document).ready(function () {
    $('.doTooltip').tooltip();
});

This works great. However when I load some additional content into the page via AJAX, any new elements with the doTooltip class applied will not have .tooltip() executed against them, since they were loaded after the ready() event.

How can I instruct jQuery to apply .tooltip() to newly loaded elements which use doTooltip?

Or is the only solution to tuck the supplied code into a function, and call this function each time I load new content into the page? I'm hoping there is a better way than this, because I use the supplied code globally.

Laurence Frost
  • 2,380
  • 3
  • 24
  • 37
  • Have you tried calling it after Ajax call finishes? – Stephen Zeng Jul 11 '16 at 16:31
  • Which tooltip plugin are you using? If twitter bootstrap one, then you can pass selector option to delegate it at any static container level, e.g: `$('body').tooltip({selector:'.doTooltip'});` – A. Wolff Jul 11 '16 at 16:32
  • It is possible to listen for the DOMNodeInserted event. See this thread: http://stackoverflow.com/questions/15268661/jquery-on-create-event-for-dynamically-created-elements. This may not be the best way but I'm not aware of any other way without applying the tooltip manually. – Sammy Jaafar Jul 11 '16 at 16:34
  • _"However when I load some additional content into the page via AJAX"_ Have you tried calling `.tooltip()` on additional content? See also http://stackoverflow.com/questions/37452164/call-function-on-change-of-value-inside-p-tag/ – guest271314 Jul 11 '16 at 16:45
  • Can you include AJAX portions of `javascript` which add new content to `document`? – guest271314 Jul 11 '16 at 16:57
  • @A.Wolff thank you this worked perfectly. If you write this as an answer then I'll accept it at the correct answer. – Laurence Frost Jul 11 '16 at 17:15

1 Answers1

0

You must use "jquery.fn.on". The example goes like this:

$(document).on('mouseover', '.doTooltip', function(){
    $(this).tooltip();
});

Please let me know if it works. It worked for me when I faced a similar issue.

If your inner-soul does not accept this hack please associate an observer on document body to poll for the addition of a new "doTooltip" element and apply tool tip to the newly inserted element. Please let me know if you need the code for the observer approach.

ajaysinghdav10d
  • 1,285
  • 3
  • 19
  • 28