Behavior to use .insertAfter() on load + after each ajax call? So I have a views page that outputs some elements in the grid. And I have a custom block on the page that needs to be inserted between those elements. On load it using .insertAfter() to randomly insert that block between view content element in the grid.
The problem is it works on load, but after each Ajax call on the pager i want to insert same block again in the grid, but that elements does not exist anymore. Not sure how to resolve this. Here is my code:
Drupal.behaviors.modalYoutubeVideo = {
  attach: function (context, settings) {
    function moveTileBetweenElements() {
      // Get random number between 1 and 23 and insert after that :nth-child.
      var rndInt = Math.floor(Math.random() * 23) + 1
      var wrapper = $('.view-products .view-content a:nth-child(' + rndInt + ')');
      var tile = $('.block-custom-order-tile');
      $(tile).insertAfter($(wrapper));
    }

    moveTileBetweenElements();
    
    $(document).once('weberAjaxViews').ajaxComplete(function (event, xhr, settings) {
      moveTileBetweenElements();
    });
  }
};
In Drupal ajaxComplete() is not required, as Drupal executes each iteration of Drupal.behaviors.*.attach() whenever an ajax call is complete. This function receives an argument, context, which on page load contains the entire contents of the document, and on AJAX calls contains the new part of the DOM being inserted into the page. This piece of the document can be parsed for the elements you are searching for. These two APIs are combined with jQuery.once() to ensure that code is not executed on any piece of the DOM more than once.
Example:
(function ($, Drupal) {

  /**
   * Does something.
   *
   * @param DOMelement context
   *   Contains a the full document on page load, or new parts of the
   *   DOM being inserted into the page after ajax calls.
   */
  function doSomething(context) {
    $(context).find(&quot;.some_dom_element&quot;).once(&quot;arbitrary-key&quot;).each(function () {
      // Do some stuff a single time on each instance of .some_dom_element that
      // appears on the page, both on page load and after any ajax loads.
    });
  }

  Drupal.behaviors.someArbitraryKey = {
    attach: function (context) {
      doSomething(context);
    }
  };
}(jQuery, Drupal));

Note that if you create your own ajax calls, you will need to pass any new parts of the DOM to Drupal.attachBehaviors():
$.ajax({
  url: '/path/to/ajax/callback',
  complete: function (data) {
    var newContent = $(data);
    // Pass the DOM element the jQuery object contains,
    // not the jQuery object:
    Drupal.attachBehaviors(newContent.eq(0));
    newContent.insertAfter($(&quot;#some_element&quot;));
  }
});