JQuery - using .on with inserting elements

I have a function that creates a tooltip for specific objects. I am currently running a tooltip function after pasting ajax to create and add new tooltip objects. I'm curious if there is a way to use .on () to automatically launch the tooltip function when pasting, rather than manually launching it.

For instance:

$('[title]').on('inserted', function(){ tooltip(this); }); 

I read a little, and it looks like these might be regular triggers, but I would like it if that were so :)

+6
source share
2 answers

Here's the pseudo code as requested.

 $(document).ready(function() { $('body').on('added','*',function() { console.log($(this),'has been added'); }); $('body').append('<div>This is the first div</div>'); }); (function($) { fncs = { append:$.fn.append, appendTo:$.fn.appendTo // etc. } // we're assigning the original functions in this // object to be executed (applied) later $.fn.append = function() { fncs.append.apply(this,arguments); $(this).children().last().trigger('added'); return $(this); } $.fn.appendTo = function() { fncs.appendTo.apply(this,arguments); return $(this); // no need to trigger because this function calls the one // above for some reason, and it taking care of the // triggering the right element(s I think) } })(jQuery); 
+1
source

This is not the answer you are looking for, but I will not attach tooltips directly to the elements. Instead, I would use a class for those that want the tooltip to appear when the mouse hovers and use the .on() event handler as follows:

 $('body').on('mouseover','.tooltip',function() { // show tooltip console.log($(this).data('tooltip')); return false; }).on('mouseout','.tooltip',function() { // hide tooltip return false; }); 

So, whatever you add to the body (not necessarily as a direct child), this trigger will handle the event.

I would simply create an additional function to assign tooltip data to each element along with the class.

 $.fn.extend({ tooltip:function(text) { text = text || ''; return $(this).each(function() { $(this).data('tooltip',text).addClass('tooltip'); }); } }); $('#someID').tooltip("Click me!"); $('button').tooltip("I'm a button"); 
0
source

Source: https://habr.com/ru/post/916313/


All Articles