1

What I want to do is have a "live" function that monitors the existance of a classname, and if any event causes that classname to be added anywhere in the DOM, another function will be fired.

How do I write a function that does that?

HandiworkNYC.com
  • 10,914
  • 25
  • 92
  • 154

2 Answers2

1

This kind of functionality does not exist in jQuery and will not be added because the methods required to implement it are depreciated by browsers. Source: https://forum.jquery.com/topic/a-global-event-or-simple-callback-for-new-content-entering-the-page-specifically-for-applying-widgets-and-behaviour#14737000003041291

However, on that same post, there's mention of a plugin that does this.

https://github.com/snesin/jcade

Kevin B
  • 94,570
  • 16
  • 163
  • 180
  • I think the OP is looking for a class that is added, not a dom added event. – LoveAndCoding Feb 14 '12 at 17:00
  • It's the same thing, that would be a DOM Mutation event, unless the class is always added by the addClass method. What happens when the class appears when a new element is added? – Kevin B Feb 14 '12 at 17:02
  • Ah, yeah, I was just looking at the plugin, which looks like it only supports `DOMContentInserted` and `DOMContentRemoved`. It should be a Mutation event (and would probably need to check on insert too). – LoveAndCoding Feb 14 '12 at 17:06
1

You have two options for listening for a classname.

  1. Run a timer and check for new elements with that class at the interval. If you find new elements, trigger the function
  2. Listen for the same event they are listening for. From there, you can check for new elements or you can assume it ran and run your function regardless.

Other than that, there is no way of 'hooking into' another element very easily. In theory, if they have not wrapper their code in a closure, you could do the following:

var _theirfunction = theirfunction;
function theirfunction () {
    // You function to override theirs
    _theirfunciton(); // Run their code. Make sure to pass along the arguments
    yourFunction();
}

Though when they update it, you would need to make sure the parameters match, and the function name is the same. This is also subject to issues depending on how they handle their function and how it is called. You would need to do an apply if this is within a specific context.

LoveAndCoding
  • 7,857
  • 2
  • 31
  • 55