Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery - using .on with element insertion

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 :)

like image 861
Pete Lada Avatar asked May 22 '12 01:05

Pete Lada


People also ask

What is the use of .on in jQuery?

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.

Which jQuery method would insert a new Li item between the two elements?

Answer: Use the jQuery append() Method You can simply use the jQuery append() method to add <li> elements in an existing <ul> element.

What is insertAfter in jQuery?

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.


1 Answers

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);
like image 142
inhan Avatar answered Sep 20 '22 13:09

inhan