Home > database >  Why jQuery not working in Ajax loaded content?
Why jQuery not working in Ajax loaded content?

Time:11-15

I am trying to insert the div after every X number of widget-box inside:

#activity-filterable-list .grid .grid

This content is BuddyPress activity and it loads in Ajax I believe, so jQuery fires up faster than the content is loaded in page, finds nothing and does nothing.

Jquery

jQuery(document).ready(function($) {
$('#activity-filterable-list .grid .grid').children(':eq(2)').after('<button>button</button>');
});

HTML

<div id="activity-filterable-list" >
<div >
<div >
<div >Box</div>
<div >Box</div>
<div >Box</div>
<div >Box</div>
<div >Box</div>
</div>
</div>
</div>

Is there a wordaround?

CodePudding user response:

I'd do something like this:

function waitFor(selector, callback) {
  if ($(selector).length) {
    callback();
  }
  else {
    // repeat wait
    setTimeout(function () {
      waitFor(selector, callback);
    }, 100);
  }
}

waitFor('#activity-filterable-list', function() {
  //.. do whatever you want
});

CodePudding user response:

As you said you want to add button div after every X number of widget-box.

So do it like below:

var counter = 1;
$('#activity-filterable-list .grid .grid').find('.widget-box').each(function() {
  if (counter % 2 == 0) {
    $(this).after('<button>button</button>');
  }
  counter  ;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="activity-filterable-list" >
  <div >
    <div >
      <div >Box</div>
      <div >Box</div>
      <div >Box</div>
      <div >Box</div>
      <div >Box</div>
    </div>
  </div>
</div>

Note: you need to apply this code when BuddyPress activity loads the above HTML through Ajax.

Reference : https://api.jquery.com/ajaxcomplete/ OR https://www.geeksforgeeks.org/jquery-ajaxsuccess-method/

  • Related