javascriptjqueryhtmlmasonryimagesloaded

Split divs with class from html to be used by script


I am trying to build my own 'infinite scroll' so I have more control than using a plugin.

I currently have the below:

$(window).scroll(function(){
      if  ($(window).scrollTop() == $(document).height() - $(window).height()){
         loadNew();
      }
}); 

function loadNew(){  
    var next = $('a.next').attr('href');

    $.ajax({
        url: next,
        success: function(html){

            ** GET ALL '.grid-item' TO USE BELOW**

            var $newElems = $( **ALL .grid-item** ).css({ opacity: 0 });
            $newElems.imagesLoaded(function(){
                $newElems.animate({ opacity: 1 });
                $container.masonry( 'appended', $newElems, true );
            });
        }
    });
    return false;
}

This is so far triggering when the user scrolls to the bottom of the page, its then getting the 'next' URL from the pagination and returning the full HTML of the page in the success call.

As you can see in my code, I want to get all divs with the class '.grid-item' to be used by the code below.

I am really struggling to get the '.grid-item' divs seperated to be used.

Is anyone able to explain how I can do this?


Solution

  • What you can do is convert the returned html to a jQuery object so that you can parse it using find() to get the relevant elements. This is done easily by wrapping the html like this, $(html), but if there is a doctype declaration then that will break it. What I normally do is make sure I've only got data that starts from the opening html tag.

    Try this...

    function loadNew(){  
        var next = $('a.next').attr('href');
    
        $.ajax({
            url: next,
            success: function(html){
                html = html.substr("<html");    // remove the doctype
                var $newElems = $(html).find(".grid-item").css({ opacity: 0 });
                $newElems.imagesLoaded(function(){
                    $container.append($newElems).masonry("appended", $newElems, true);
                    $newElems.css({ opacity: 1 });
                });
            }
        });
        return false;
    }
    

    Also, you need to first append the elements to the container, and then tell masonry that you've done so. The masonry appended call doesn't actually append anything.