3

I have a third party function that I use. To use ii I just run:

$('.myElements').thirdPartyFunction(options);

It works fine. However if I dynamically add an element with class .myElements, how can I have it run the thirdPartyFunction on that that element?

Castro Roy
  • 7,623
  • 13
  • 63
  • 97
KingKongFrog
  • 13,946
  • 21
  • 75
  • 124
  • 3
    `$('.otherElements').addClass('myElements').thirdPartyFunction(options);` I don't believe there are shortcuts – Alon Eitan Jul 19 '16 at 21:53
  • That is manually running it. How do I listen if elements have been added with that class and then run the function. – KingKongFrog Jul 19 '16 at 21:56
  • The short answer is, you can't. You have to track when elements with that class have been added and run the third party function on it again. You could look into using a [`MutationObserver`](https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver) to help with that, but it might be more trouble than it's worth, depending on the size of your code base. – Heretic Monkey Jul 19 '16 at 22:00
  • What function add the new element? Is a function created by you? If yes, it is the right place to run your `thirdPartyFunction` – Castro Roy Jul 19 '16 at 22:04
  • Unfortunately this is a chrome extension I'm writing that runs on a third party site. – KingKongFrog Jul 19 '16 at 22:05

1 Answers1

1

If you're not worried about performance you can use DOMNodeInserted

$(document).bind("DOMNodeInserted"), function(event){
      $(event.target).find(".myElements").addBack(".myElements").thirdPartyFunction();
}

Though it is not very performant, so you may wish to look at something else.

Other options: Alternative to DOMNodeInserted

Community
  • 1
  • 1