jQuery selector not working on ajax loaded content – lazy loading / infinite scroll

I have a page full of elements that I filter by the classes. This works great, however there are too many elements on the page and so I have implemented lazy loading using ajax. The problem is, the filters do not work on the content loaded via ajax.

The problem seems to be that the $divs = $(‘.box’) are not being selected.

Can anyone help?

JQuery for filterng divs.

jQuery( function( $ ) {

var $divs = $(‘.box’);

//filter multiple divs on select
var $selects = $(‘.filter_dd’).on(‘change’, function() {

var css_list_array = [];
$selects.each(function(index){

if ($(this).has(‘option:selected’)){

if( $(this).val() !== ” ) {
var css = ‘.’ + $(this).val();
var found = $.inArray(css, css_list_array);
if(found < 0) {
//if not already in array – add it
css_list_array.push(css);
}
}
}
});
var css_string = css_list_array.join(”);
console.log(css_string);
var $el = $(css_string); //selected CSS names
console.log($divs); //divs not being selected as this is empty
$divs.removeClass(‘is-animated’).fadeOut().promise().done(function()
{
if(css_string == null || css_string==”){
$divs.addClass(‘is-animated’).fadeIn();
} else {
$el.addClass(‘is-animated’).fadeIn();
}
});
});
});

Ajax code:

jQuery(document).ready(function($) {

//find scroll position
$(window).scroll(function() {
//init
var that = $(‘#loadMore’);
var page = $(‘#loadMore’).data(‘page’);
var newPage = page + 1;
var ajaxurl = $(‘#loadMore’).data(‘url’);
//check if scrolled
if ($(window).scrollTop() == $(document).height() – $(window).height()) {

$.ajax({
url: ajaxurl,
type: ‘post’,
data: {
page: page,
action: ‘resources_load_more’
},
error: function(response) {
console.log(response);
},
success: function(response) {
console.log(response);
//check
if (response == 0) {
//check
if ($(“#no-more”).length == 0) {
$(‘#ajax-content’).append(‘<div id=”no-more” class=”text-center”><h3>You reached the end of the line!</h3><p>No more posts to load.</p></div>’);
}
$(‘#loadMore’).hide();
} else {
$(‘#loadMore’).data(‘page’, newPage);
$(‘#ajax-content’).append(response);
}
}
});
}
});
});

Read more here:: jQuery selector not working on ajax loaded content – lazy loading / infinite scroll

Leave a Reply

Your email address will not be published. Required fields are marked *