3

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.

2 Answers2

2

Keep it simple and stupid

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

Docs here

EDIT

Possible Duplicate Of this

Community
  • 1
  • 1
wilson
  • 334
  • 1
  • 15
  • I need to do stuff multiple times (on scroll event) and at different times after "ajaxComplete" and not just once, so this wont do it. – psyduck.the.apex.predator Aug 10 '15 at 13:14
  • You can check [Here](http://stackoverflow.com/questions/17821411/what-is-a-proper-way-to-add-listeners-to-new-elements-after-using-ajax-to-get-th) or [here](http://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) – wilson Aug 10 '15 at 13:18
  • Checked it and it is exactly what Im doing, weird thing is that CLICK event works perfectly, but SCROLL event does not. – psyduck.the.apex.predator Aug 10 '15 at 13:22
  • 1
    This is the correct answer. You need to bind your event on element creation. The Scroll as well as other do not event bubble properly. – eagle12 Aug 10 '15 at 13:42
1

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.

Zoran P.
  • 870
  • 1
  • 13
  • 16
  • 1
    it has no been addressed for 2 reasons: 1. Noone answered him why scroll is not working while click is 2. I did not said to do it on AjaxComplete but basically whenever he creates a new element. He must know when he created new element, and therefore he knows that he can call ".on()" after that... as simple as that. – Zoran P. Aug 10 '15 at 13:51
  • Actually if you look at my comment below it states exactly what you said. Simple as that. – eagle12 Aug 10 '15 at 14:07