Yin Yang Yin Yang - 1 month ago 7
Ajax Question

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?

Answer

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