Yin Yang
Yin Yang

Reputation: 1806

document.ready() equivalent for AJAX loaded content

I have a AJAX call that adds nested divs (with the class .song_block) to a div (#song_list) on the page. I have a button that I want to hide once the count of nested divs reaches a certain number.

Here is my script

<script type="text/javascript"> 
    $(document).ready(function() {
        if($("#song_list").find('.song_block').length == 100){
            $('#loadmore').hide();
        }       
    });
</script>

Here is the AJAX call

<script type="text/javascript">
    $(document).ready(function() {
        $('#loadmore').on('click', function() {
            $('#loadmore').hide();
            $('#loadmore-gif').show();
            $.ajax({
                type: "GET",
                url: "/loadmore/",
                data: {
                    'slug': $('.dj_slug').text().trim(),
                    'song_rank': $("#song_list").find('.song_block').length
                },
            }).done(function (response) {
                $('#song_list').append(response);
                $('#loadmore').show();
                $('#loadmore-gif').hide();
            });
        });
    });
</script>

Now this doesn't work since $(document).ready() doesn't work for AJAX loaded content. How can I handle such a situation using javascript?

Upvotes: 2

Views: 5667

Answers (2)

Imran Zahoor
Imran Zahoor

Reputation: 2797

The equivalent to $(document).ready for AJAX is ajaxComplete. So here is the code:

$(document).ajaxComplete(function(){
    //your code here
});

Thanks to @usman on the answer here Document Ready equivalent for ajax-loaded content via jQuery Mobile accordion

Upvotes: 3

Yury Tarabanko
Yury Tarabanko

Reputation: 45106

Create a function

function hideLoadMore() {
    if($("#song_list").find('.song_block').length == 100){
        $('#loadmore').hide();
    } 
}

And use it when DOM was loaded and when related ajax requests are done

$(hideLoadMore);

$(function() {
    $('#loadmore').click(function(){
        $.ajax(...).done(/*perform dom insertion*/).done(hideLoadMore);
    });
});

Upvotes: 0

Related Questions