Paul
Paul

Reputation: 1047

Infinite scrolling and breaking my other JS

I'm using: https://infinite-scroll.com and run into a problem I can't work out.

The infinite scroll works well and here is my initialisation:

var $container = $('.parent').infiniteScroll({
  path: '.nav-prev a',
  append: '.article',
    status: '.scroller-status',
  hideNav: '.navigation-index',
});     

After it loads the first page it breaks my other JS. ie I have a click function on "article"

    $(".article").click(function(){
        $(".hidden").hide("fast");
        $(this).next('.hidden').slideToggle("fast");
    });

After the scroll kicks in this stops working.

I've tried various things such as:

var $container = $('.parent').infiniteScroll({
    $(".article").click(function(){
    $(".hidden").hide("fast");
    $(this).next('.hidden').slideToggle("fast");
    });
});

But I just can't get it to use my JS. I know I'm missing something?

Upvotes: 1

Views: 284

Answers (2)

imvain2
imvain2

Reputation: 15857

This is actually a very common problem. The problem is jquery event handlers are added to the objects in the DOM at the time the event handler is added. Which means after you add new objects, the new ones don't get the event handler.

Luckily, there is a simple solution, modify your event handler as follows using Delegated event handlers:

$(document).on("click",".article",function(){

Or I suppose adding it to the .parent is probably better instead of adding it to the document.

$(".parent").on("click",".article",function(){

Either way should work but document will work for sure.

so:

$(".parent").on("click",".article",function(){
    $(".hidden").hide("fast");
    $(this).next('.hidden').slideToggle("fast");
});

or:

$(document).on("click",".article",function(){
    $(".hidden").hide("fast");
    $(this).next('.hidden').slideToggle("fast");
});

Upvotes: 5

Paul
Paul

Reputation: 1047

For anyone else with similar issue my final snippet is:

$(".parent").on("click",".article",function(){
    $(".hidden").hide("fast");
    $(this).next('.hidden').slideToggle("fast");
});

Upvotes: 0

Related Questions