Olli Olli - 1 year ago 81
jQuery Question

how to update waypoint position after adding masonry elements dynamically

I am currently trying to build a mobile page with a pinterest style look to display images.

To be able to show images of different dimensions in specific columns i decided to use masonry as layout engine.
To trigger loading of new elements I chose waypoints

Adding elements dynamically to my masonry container works well (when using a button to add them).

When I setup a waypoint at the end of my container to automatically fill in new elements, this waypoint gets triggered wenn i scroll to it the first time (div with black background at the bottom of the page).

layout with waypoint div after initial setup

After the elements are being added, the waypoint is not updated to point to the bottom of the page again. Instead it seems to stick to the original position before adding the new elements.

When you take a look at my jsfiddle, you can see exactly this behaviour:
Elements get added to the container upon loading. When you scroll down you will reach the waypoint (black bar to make it visible) and there are new elements being added to the end of my masonry container.
When you scroll down again to the bottom (black bar again), nothing happens.
After scrolling up to the top of the page and back down, you will see that the waypoint gets triggered again at the middle of the page (old position of the waypoint).

layout after waypoint got triggered first time

As far as I understand the waypoints, it looks like i have to reset / recalculate the waypoint again after changing the DOM, so I tried adding

in line 51 after the elements being added, but this results in the browser hanging and triggering the waypoint directly for a lot of times (over 200), so be aware when you remove that comment that your browser may stuck or crash...

So finally here is the question: How can i add my elements dynamically and still update the waypoint to be able to lazy load new elements, whenever i scroll to the bottom?

Answer Source

Destroy the waypoint at the end and then rebuild it

Replace the set timeout function at the end of your script like this

var footerWaypoint = $('#nextImageResults');
footerWaypoint.waypoint(getNextResults, {
    offset: '100%'

function getNextResults(direction){
    if(direction == "down") {
        $('#imageListContainer').css('background-color', 'red');
        var elems = addElements(20);
        addMasonry('#imageListContainer', elems);
        $('#imageListContainer').css('background-color', 'green');
        footerWaypoint.waypoint(getNextResults, {
           offset: '100%'

Answer from Reinit Reinitialize waypoint