1

I have a view of nodes with an AJAX on scroll set up. Everytime a person scrolls down the page new elements inside a view show up (e.g. nodes).

I'm trying to add a new class only to new nodes that show up after each AJAX call. So far I've only managed to add a class to all nodes inside a view using drupal.behaviors, even the ones that were originally visible in the DOM(before AJAX call).

What am I missing?

My current code:

 $(document).ready(function($) {
    $('.views-infinite-scroll-content-wrapper').find('.views-row').addClass('i-was-here-first');
});

  Drupal.behaviors.testing = {
    attach:function (context, settings) {
      $('.views-infinite-scroll-content-wrapper', context).find('.views-row').addClass('i-was-here-second');
    }
};
1

Taking a blind guess: Your context matches the entire parent container, so you can't filter by "new ones only" with context. But as a workaround you could specify a more explicit find to filter only new ones:

This will add .i-was-here-first to every views row present on document ready:

 $(document).ready(function($) {
    $('.views-infinite-scroll-content-wrapper').find('.views-row').addClass('i-was-here-first');
});

Now use that class to filter sub-sequent behavior calls by using a more explicit find():

Drupal.behaviors.testing = {
    attach:function (context, settings) {
      $('.views-infinite-scroll-content-wrapper', context).find('.views-row:not(.i-was-here-first)').addClass('i-was-here-second');
    }
};

Side note:
I'd recommended not to use $(document).ready() at all in Drupal because this might cause problems when using BigPipe module, which is active by default. Drupal will initially trigger all behaviors with document as context, so you should use something like this instead:

Drupal.behaviors.instead_of_document_ready_do_this = {
  attach: function (context, settings) {
    $(document, context).once('my_unique_name').each( function... );
  }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.