0

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.

Oliver Kucharzewski
  • 2,523
  • 4
  • 27
  • 51

1 Answers1

2

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.

Community
  • 1
  • 1
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Hi Barmar, Thanks for the event note. I currently have events though; however they aren't working as they are run on document.ready() and once new elements are generated the events no-longer work on the new buttons. $(".search-btn").on('click', function () { alert("test"); }); Once there is a new search-btn, it doesn't work unless I rerun the function. – Oliver Kucharzewski Nov 01 '16 at 01:19
  • That's why you should use event delegation, as explained in the linked question. – Barmar Nov 01 '16 at 01:22
  • $('body').on('click','.search-btn',fn) – gu mingfeng Nov 01 '16 at 01:24
  • Apologies - i totally misread the second argument. This is AMAZING. Thank you! – Oliver Kucharzewski Nov 01 '16 at 01:27