Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create scroll event on dynamically (AJAX) generated element?

I need to do stuff when dynamically generated #random scrolls, but .on does not work

Doesn't work ->

$staticParent.on("scroll", #random, function()
{
  //do stuff
});

Works ->

$staticParent.on("click", #random, function()
{
  //do stuff
});

A) I would like to know why the first example (scroll) doesn't trigger the event and the second one (click) does.

B) Am I doing something wrong or is there any .on (non-deprecated) alternative I could use?

BTW - I have read and tried other related topics here, but nothing worked so far.

like image 273
psyduck.the.apex.predator Avatar asked Apr 18 '26 06:04

psyduck.the.apex.predator


2 Answers

Keep it simple and stupid

$(document).on('ajaxComplete', function(){ /*Your code here*/ });

Docs here

EDIT

Possible Duplicate Of this

like image 175
wilson Avatar answered Apr 19 '26 21:04

wilson


Scroll (as well as load and error) does not bubble up. There are few approaches out there, but my personal favorite would be to rerun the on function after scroll. So basically:

function AddRandomEl()
{
  // do your magic here
  $staticParent.on("scroll", #random, function()
{
  //do stuff
});
}

If your random is a class not an element then you would need ".off" before, or you would have it fire twice on those which pre-existed.

like image 36
Zoran P. Avatar answered Apr 19 '26 21:04

Zoran P.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!