How to prevent Infinite Scroll from loading pages when the tab is not active?

问题: I am working on a website with Bootstrap 4 and jQuery, so basically there are 3 tabs and each one of them contain masonry elements that are loaded on scrolling with Infinit...

问题:

I am working on a website with Bootstrap 4 and jQuery, so basically there are 3 tabs and each one of them contain masonry elements that are loaded on scrolling with Infinite Scroll plugin. I am basically looking for a way to allow Infinite Scroll to load tab content only if the tab is active. So let's say my html looks like this:

<div class="tab-content" id="v-pills-tabContent">
    <div class="tab-pane fade show active" id="v-pills-home" role="tabpanel" aria-labelledby="v-pills-home-tab">
        <div class="grid" id="grid1">
            <!-- PHP script that generates the content for each element in that tab -->
        </div>                          
    </div>
    <div class="tab-pane fade" id="v-pills-profile" role="tabpanel" aria-labelledby="v-pills-profile-tab">
        <div class="grid2" id="grid2">
        <!-- second PHP script that generates the content for each element in that tab-->
        </div>
    </div>
    <div class="tab-pane fade" id="v-pills-messages" role="tabpanel" aria-labelledby="v-pills-messages-tab">
        <div class="grid3" id="grid3">
         <!-- third PHP script that generates the content for each element in that tab -->
        </div>
    </div>
</div>

To initialise masonry and Infinite Scroll, I am using the bootstrap event shown.bs.tab this way:

$("#v-pills-profile-tab").on('shown.bs.tab', function () { 
    grid.infiniteScroll({
        path: '.pages'
        //other parameters
    });
});

However once initialized, Infinite Scroll doesn't care if the tab isn't shown anymore and keeps loading content in the background, which messes up all my masonry layout and makes the website load content unnecessarily.

So I tried the following condition with $("#v-pills-profile"):

$("#v-pills-profile-tab").on('shown.bs.tab', function () 
{ 
    if($("#v-pills-profile").hasClass("active"))
    {
        grid.infiniteScroll({
            path: '.pages'
            //other parameters
        });
    }
}

But the issue remains the same, it seems like if Infinite Scroll is initialized once, it will just carry on with loading pages even if $("#v-pills-profile") loses its "active" class.

Any advice or help would be much appreciated. Thanks.


回答1:

Have you tried to initialize only the .grid element contained in the activated tab?

$("#v-pills-profile-tab").on('shown.bs.tab', function() { 
    var activeGrid = $('.tab-pane.active').children('.grid');
    if (!InfiniteScroll.data(activeGrid[0])) {
        activeGrid.infiniteScroll({...});
    }        
}
  • 发表于 2019-02-17 03:31
  • 阅读 ( 262 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除