Oliver Kuchies Oliver Kuchies - 1 month ago 6
Javascript Question

Run a Javascript function after a default jQuery function is run

in jQuery; How would I execute a function once a specific function is run. For example; everytime

.text()
is run, can I run a function no-matter the context?

In this specific example i'm looking to listen to
.append()
, reason being I need to re-register event listeners when new elements are placed on the screen. (i.e. btn click event listeners).

How can I accomplish this? Let us use
refreshEvents()
as an example function.

Answer

Probably the right way to do what you want is with event delegation, as described in Event binding on dynamically created elements?. E.g. change

$(".search-btn").on("click", function() {
    ...
});

to:

$("#container").on("click", ".search-btn", function() {
    ...
});

Replace #container with a selector for a static element that contains all the dynamically-added search buttons.

But to show how to do what you asked, you can do:

(function(oldappend) {
    $.fn.append = function() {
        var result = oldappend.apply(this, arguments);
        refreshEvents();
        return result;
    };
})($.fn.append);

This saves the original value of the jQuery .append() method in the local variable oldappend, then redefines it to a function that calls the original function and then calls your function.

Comments