Arete Arete - 6 months ago 46
Javascript Question

jQuery does not work with infinite scroll

I have just made a new wordpress theme and I am using the following script to get an accordion-like effect.

( function( $ ) {
var $ele = $('.entry-content').hide();
$(".entry-header").click(function(e) {
e.preventDefault();
var $ele1 = $(this).parents(".post").children('.entry-content').slideToggle('fast');
$ele.not($ele1).slideUp();
});
} )( jQuery );


I just activated jetpack's infinite scroll. The jquery script does not work on newly loaded content added by infinite scroll. My guess is that the script has to be reloaded, or at least triggered, whenever new content is added by infinite scroll. I have searched the web this whole day without finding any solution. Any help here would be appreciated.

I have enqueued my .js in my functions.php like this:

function journial() {
wp_enqueue_script( 'journial', get_template_directory_uri() . '/js/journial.js', array( 'jquery' ), '1.0.0', true );
}
add_action( 'wp_enqueue_scripts', 'journial' );


Test site: here

Answer

You need to trigger an event after posts are appended. To make use of this event, simply catch the post-load event when it fires on document.body:

(function($){ //wait until dom has loaded 

  function initAccordion(){ // first, prepare your function 
    var $ele = $('.entry-content').hide();
    $(".entry-header").unbind('click').click(function(e) { // bind click event handler 
      e.preventDefault();
      var $ele1 = $(this).parents(".post").children('.entry-content').slideToggle('fast');
      $ele.not($ele1).slideUp();
    }); 
  } 

  initAccordion(); // second, run the function the first time page loads 
  
  $(document.body).on('post-load', function(){// third, setup event handeler 
  initAccordion(); //run the funtion again after new content is loaded 
  }); 

} )(jQuery);