Search code examples
jqueryis-empty

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?


Solution

  • 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.