I have a function which creates a tooltip for specific objects. Currently, I am running a tooltip function after ajax insertions to create and append the new tooltip objects. I am curious if there is a way to use .on() to auto-run the tooltip function on insertion, rather than manually running it.
For instance:
$('[title]').on('inserted', function(){
tooltip(this);
});
I did some reading and it looks like custom triggers might be the way to go, but I'd love if it something like this existed :)
The on() is an inbuilt method in jQuery which is used to attach one or more event handlers for the selected elements and child elements in the DOM tree.
Answer: Use the jQuery append() Method You can simply use the jQuery append() method to add <li> elements in an existing <ul> element.
jQuery insertAfter() Method The insertAfter() method inserts HTML elements after the selected elements. Tip: To insert HTML elements before the selected elements, use the insertBefore() method.
Here's the pseudo code as per request.
$(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's taking care of the
// triggering the right element(s I think)
}
})(jQuery);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With