简体   繁体   中英

Actively looking for when a div is empty with jQuery (simple) .is('empty')

I need to initiate an ajax call once a div is empty (involving an animation).

if($(document).find('h2').is(':empty')) {
     //do something
};

The only issue is, the way this statement is setup, it only looks once the document is ready. I'm trying to do this without using a setTimeout function.

For example, I know if I want to do something when a select dropdown is changed, I can use: $('select').change(). Any ideas?

There is no reasonable way to do this currently; checking with an interval is the only reliable solution, and even that leaves a lot to be desired technically.

DOM Mutation Observer would let you solve this problem easily and without any constraints, but browser support is less than ideal.

The best approach today (if possible in your scenario) would be to hook into the code that empties the element and have it invoke your callback when the time has come.

If typer.js provides source code that you can hook into, I would have it trigger a custom event that you can then listen for in your code.

I imagine there would be some for loop that deletes each character one by one, so at the end of the loop you can do something like:

for(var i = 0; i < $('#divId').innerText.length; i++){
...
}

$(document).trigger('YourCustomEvent');

And on your end, you can bind to the custom event thusly:

$(document).on('YourCustomEvent', YourCallBackFunction);

And then handle the callback:

function YourCallBackFuntion(){...
}

The beauty of this approach is that you don't even have to define your custom event, you just have to make sure the binding matches up.

I dug a bit deeper, and found this solution here: What's the easiest way to call a function every 5 seconds in jQuery?

window.setInterval(function(){
  if($(document).find('h2').is(':empty')) {
     //do something
  };
}, 5000);

Not a light solution, however it is not run for very long.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM