8

I'm making a simple little website to apply a different formatting style to Reddit posts, I'm trying to add the infinite-scroll jQuery plugin but it doesn't do anything. I tried following the (very simple) instructions on the infinite-scroll page and when it didn't do anything I thought I must have entered something wrongly, but then I just copy/pasted the code from the Masonry/Infinite-Scroll example and it still didn't work. Masonry is working perfectly (finally) but I just can't figure out what is wrong with infinite-scroll. I understand the basics of jQuery and JavaScript, but obviously not as much as most of you people, so could you please help me out and let me know what is wrong? My site is live at reddit.ymindustries.com.

Thanks heaps, you guys have rarely failed me so far.

YM

EDIT: If there aren't enough images to fill up the page on the homepage, visit reddit.ymindustries.com/r/aww for more images.

EDIT 2: I believe I located the issue, it is described here: https://github.com/paulirish/infinite-scroll/issues/5 Now to figure out a fix...

EDIT 3: Added a little bit of a hack in to make it sort of work, but it just seems to loop the second page endlessly now. Hmm...

Joshua Walsh
  • 1,915
  • 5
  • 25
  • 50
  • 3
    Your site might get down one day and this question could be totally useless for future generations – Roko C. Buljan Aug 18 '12 at 13:57
  • 1
    On a large monitor's screen, there are never enough items for even regular scrolling to kick in. Infitite scroll is for appending new elements to the #container - it gets longer and longer by more elements being appended to it past the window bottom. – Systembolaget Aug 18 '12 at 16:16
  • @Systembolaget That is correct, you identified my problem. I posted a solution below. – PJ Brunet Jan 18 '15 at 21:03

4 Answers4

0

I think your problem is actually css. Make your page longer that client area height. add more images to $container

Point is, botom edge of your $container need to pass bottom of window so scroll event fires so infinite scroll can react on this event and calculate weather or not edge is reached

BTW, in same cases, for instance, when I shrink my window, the example you set is working.

=== UPDATE ===

I found some time to play with infinitescroll and here is final working script, just set pathParse method in your script

$(function () {

        var $container = $('#itemContainer');

        $container.imagesLoaded(function () {
            $container.masonry({
                itemSelector:'.item'
            });
        });
        $container.infinitescroll({
                    navSelector:'.navigation', // selector for the paged navigation
                    nextSelector:'.navigation #next', // selector for the NEXT link (to page 2)
                    itemSelector:'.item', // selector for all items you'll retrieve
                    bufferPx:40,
                    debug:true,
                    columnWidth:function (containerWidth) {
                        return containerWidth / 5;
                    },
                    loading:{
                        finishedMsg:'No more pages to load.',
                        img:'http://i.imgur.com/6RMhx.gif'
                    },
                    pathParse: function(path,page){
                        return $(this.nextSelector).attr("href");
                    }
                },
                // trigger Masonry as a callback
                function (newElements) {
                    // hide new items while they are loading
                    var $newElems = $(newElements).css({ opacity:0 });
                    // ensure that images load before adding to masonry layout
                    $newElems.imagesLoaded(function () {
                        // show elems now they're ready
                        $newElems.animate({ opacity:1 });
                        $container.masonry('appended', $newElems, true);
                    });
                    //console.log("test (never fired :( )");
                }
        );

    });

Now, since your next link will not update by it self (http://reddit.ymindustries.com/?after=t3_yh4av), you need to change the callback to pull out last element from ajax response and change next link... could be something like this

function (newElements) {
                        // hide new items while they are loading
                        var $newElems = $(newElements).css({ opacity:0 });
                        // ensure that images load before adding to masonry layout

                        // ======> if query parameter after=... is caring filename then do this
                        var lastImageUrl= $newElements[$newElements.length-1].attr("src");
                        var lastFileName= lastImageUrl.substring(lastImageUrl.lastIndexOf("/") +1, lastImageUrl.lastIndexOf("."));
                        $("#next").attr("href", "http://reddit.ymindustries.com/?after="+lastFileName);

                        $newElems.imagesLoaded(function () {
                            // show elems now they're ready
                            $newElems.animate({ opacity:1 });
                            $container.masonry('appended', $newElems, true);
                        });
                        //console.log("test (never fired :( )");
                    }
Milan Jaric
  • 5,556
  • 2
  • 26
  • 34
  • I added more images (double the amount) so my scrollbar now goes quite far and then I also tried shrinking my browser window, but the Infinite Scrolling is still not triggered. The navigation section at the bottom of the page is not being hidden either. – Joshua Walsh Aug 19 '12 at 01:52
  • looks like infinite scroll has option "debug:true", please add it in your script it will probably output somethin like "Sorry, we couldn't parse your Next (Previous Posts) URL. Verify your the css selector points to the correct A tag. If you still get this error: yell, scream, and kindly ask for help at infinite-scroll.com." ... At least it was my case when I downloaded your code locally and tried to change it to see what is problem. – Milan Jaric Aug 19 '12 at 04:28
  • I add debug:true and suddenly it starts working... This requires further investigation. – Joshua Walsh Aug 19 '12 at 05:32
  • And then I refresh the page, exact same source code, and get the error. – Joshua Walsh Aug 19 '12 at 05:34
0

You also need to take care of wich version of infinite-scroll your using since if you use the ones that comes with masonry/isotope (version 2.0b2.110713), both need a little hack in order to call the function and not use the predefined array:

//old code, to be changed (line 489)
desturl = path.join(opts.state.currPage);
// new code
desturl = (typeof path === 'function') ? path(opts.state.currPage) : path.join(opts.state.currPage);

This is already fixed in the newer versions of infinite-scroll

bitIO
  • 384
  • 3
  • 11
0

I had the same problem with jQuery's "infinitescroll" and Masonry. You might just solve this by giving your page more initial items so that the plugin's scrolling detection kicks in.

In WordPress this is under the "Reading" settings. By default WordPress only opens 10 items at a time. You could increase that number to 100/page to be more sure the window will be full initially. I had some code here that was just horrible, turns out I just needed longer pages, not more code.

So it's difficult to test these plugins on large displays if you don't have enough images. Maybe the solution is to scale the images larger on large displays so you're more sure about getting your content below the fold.

If you think someone might get to your website with a really huge display, I'm not sure what the answer is other than showing more items/page and maybe adding $('#masonry').infinitescroll('retrieve'); to your footer to load an extra page just in case.

PJ Brunet
  • 3,615
  • 40
  • 37
  • how you resolve jQuery's infinitescroll and Masonry? @pjbrunet – bsiilvia Dec 13 '16 at 12:13
  • @SilviaBerardo I don't understand your question. – PJ Brunet Dec 13 '16 at 16:42
  • I try to use jquery's infinitescroll with masonry after render the content of masonry container but infinite scroll not found elements. I try to resolve my issue using your answer but it doesn't work. How can I resolve this problem? @pjbrunet – bsiilvia Dec 14 '16 at 09:04
  • @Silvia Berardo This particular solution says to increase the items on the page to cross "below the fold" which triggers the infinite scroll. I ended up coding my own solution which is too long to share on StackOverflow. I can fix infinite scroll problems if you contact me directly. – PJ Brunet Dec 14 '16 at 19:27
0

Try this code I think it may help:

<!DOCTYPE html>
<html>
  <head>
    <title>Infinite Scroll Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <style>
      #content {
        height: 1000px;
        background-color: lightblue;
        margin-bottom: 50px;
      }

      #loading {
        display: none;
        text-align: center;
        font-size: 18px;
        color: gray;
        margin-top: 20px;
      }
    </style>
  </head>
  <body>
    <div id="content">
      <p>Some initial content here...</p>
    </div>
    <div id="loading">Loading more content...</div>
    <script>
      // Function to check if the user has scrolled to the bottom of the page
      function isScrolledToBottom() {
        const scrollTop = $(window).scrollTop();
        const windowHeight = $(window).height();
        const documentHeight = $(document).height();
        return scrollTop + windowHeight >= documentHeight;
      }

      // Function to load additional content using AJAX
      function loadMoreContent() {
        $('#loading').show();
        $.ajax({
          url: 'load-more-content.php',
          method: 'GET',
          data: { offset: $('#content p').length },
          success: function(html) {
            $('#content').append(html);
            $('#loading').hide();
          }
        });
      }

      // Event listener for scrolling
      $(window).scroll(function() {
        if (isScrolledToBottom()) {
          loadMoreContent();
        }
      });
    </script>
  </body>
</html>

This code creates a scrolling page with some initial content in a element with an id of "content". The infinite scroll function is implemented using jQuery and AJAX.

You'll need to create the load-more-content.php script on your server to generate the additional content dynamically based on the offset parameter. This script should return the HTML content to be appended to the page.

Here is the load-more-content.php script:

<?php
// Connect to the MySQL database
$host = 'localhost';
$username = 'your_username';
$password = 'your_password';
$database = 'your_database';
$conn = mysqli_connect($host, $username, $password, $database);

// Retrieve the offset parameter from the AJAX request
$offset = isset($_GET['offset']) ? $_GET['offset'] : 0;

// Query the database for additional content
$sql = "SELECT * FROM posts LIMIT $offset, 10";
$result = mysqli_query($conn, $sql);

// Generate HTML code for the additional content
$html = '';
while ($row = mysqli_fetch_assoc($result)) {
  $html .= '<p>' . $row['title'] . '</p>';
  $html .= '<p>' . $row['content'] . '</p>';
}

// Return the HTML code to the AJAX request
echo $html;

// Close the database connection
mysqli_close($conn);
?>