Jose Calderon
Jose Calderon

Reputation: 571

Javascript 'div empty' event listener

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

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

)};

Upvotes: 0

Views: 1859

Answers (1)

JCOC611
JCOC611

Reputation: 19729

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);

Upvotes: 2

Related Questions