2

I have a function that looks for the existence and count of the class .dirty on a webpage. It would have to start at a certain point but at that point, I'd like for jQuery to observe for css changes in the DOM and rerun this function. Is this possible? Could I use on() for this? Like:

$(document).on('change','.dirty', dosomething);

although I know that's different than what change is used for. Basically, the change I want is any addClass or removeClass for 'dirty'.

sample markup

looking for observing both adding / removing .dirty on 'top-level-menu' so that I can propogate change

<div class="top-level-menu dirty" data-menu-global-id="12828">
  <input id="menu-name-global-id-12828" size="30" type="text" value="Some value here">
</div>
timpone
  • 19,235
  • 36
  • 121
  • 211
  • 1
    Unfortunately there is no method to do that nowadays. Instead - you probably would create your custom event and build your solution over it. – zerkms Oct 15 '12 at 05:07
  • I think what you are looking for has been answered here: http://stackoverflow.com/questions/2844565/is-there-a-jquery-dom-change-listener and http://stackoverflow.com/questions/5154882/how-can-i-observe-the-contents-of-an-a-tag-jquery – U.P Oct 15 '12 at 05:11
  • @UmairP - looks ugly, saw one of those but thought there would be a nicer sol'n – timpone Oct 15 '12 at 05:17

1 Answers1

1

.on would be perfect for this function, however I would try to be a little more specific about where you are expecting ".dirty" to happen. For example, if you know that dirty will only happen in the nav, only watch nav.

$('nav').on('change', '.dirty', function(e) {
    doSomething(e); 
});

View the jsFiddle.

Brian Noah
  • 2,962
  • 18
  • 27
  • thx, hmm... tried this before and wasn't working; not sure if this is supported – timpone Oct 15 '12 at 05:29
  • Yeah, I've used it before, and worked fine. Could you post your code and I'll make a js fiddle for you? – Brian Noah Oct 15 '12 at 05:35
  • @timpone jsFiddle link added. – Brian Noah Oct 15 '12 at 06:23
  • @BrianNoah OP is looking for a DOM listener so if `$('.dirty).css(.. ` makes a change the listener would catch the change. There are no such listeners in jQuery without triggering a custom event from the code that makes the change – charlietfl Oct 15 '12 at 10:46