0

Is there a way to have a listener for when a div element is empty?

 $('#myDiv').emptyEvent(function(){

)};
Jose Calderon
  • 551
  • 2
  • 5
  • 11
  • possible duplicate of [Is there a jQuery DOM change listener?](http://stackoverflow.com/questions/2844565/is-there-a-jquery-dom-change-listener) – CD.. Jan 24 '13 at 23:17

1 Answers1

2

You should run David's code inside an event handler, such as DOMNodeInserted, DOMCharacterDataModified, or DOMSubtreeModified. The latter being the most recommended. For example:

$('#myDiv').bind("DOMSubtreeModified", function(){
   if ( $('#myDiv').html() == "" ) {

   }
)};

Edit: Such implementation is however deprecated, as stated in the comments. An alternative implementation, as suggested by david, is the following:

// select the target node
var target = $("#myDiv")[0];

// create an observer instance
var observer = new MutationObserver(function(mutations) {
   mutations.forEach(function(mutation) {
      if($("#myDiv").html() == ""){
         // Do something.
      }
   });    
});

// configuration of the observer:
var config = { attributes: true, childList: true, characterData: true };

// pass in the target node, as well as the observer options
observer.observe(target, config);
JCOC611
  • 19,111
  • 14
  • 69
  • 90
  • 2
    Just be aware that those mutation events are deprecated and have been replaced by the mutation observer: https://developer.mozilla.org/en-US/docs/DOM/MutationObserver – david Jan 24 '13 at 23:20
  • 3
    And sad thing is it is [deprecated](http://stackoverflow.com/questions/6659662/why-is-the-domsubtreemodified-event-deprecated-in-dom-level-3) – epascarello Jan 24 '13 at 23:21
  • indeed they are I was just about to comment that – kidwon Jan 24 '13 at 23:22
  • @david: I edited the answer. That might work, although I'm not sure if the mutation observer is supported among other browsers... – JCOC611 Jan 24 '13 at 23:26
  • 2
    The number of davids on this site is too damn high. – david Jan 24 '13 at 23:26
  • ...so it works only in firefox :( I'm disappointed that such useful event isn't crossbrowser implemented yet – kidwon Jan 24 '13 at 23:32