For example, after using AJAX, I'll have a scrollable DIV. How to bind scroll events to it?
I've tried:
$(window).on("scroll", ".mydiv", function(){...})
$(document).on("scroll", ".mydiv", function(){...})
$(".mydiv").on("scroll", function(){...})
$(".mydiv").scroll(function(){...})
But they didn't work.
element must be exists in document before you use jquey.on().
you can insert dummy
<div class="mydiv"></div>
before you use jquery.on()I am just reviving this old question because I didn't find good answer and I struggled myself for better way to listen 'scroll' event for dynamically appended element.
Since Scroll event does not bubble up in the DOM due to this we can't use on() like we use for scroll. So I came up with listening my own custom triggered event in the element where I would want to listen the 'scroll' event.
The scroll event is binded after the element is appended on the DOM followed by triggering my own custom event.
http://jsfiddle.net/hainawa/cruut/
In my app, I have a button that appends form fieldsets to the body every time a button is clicked - I wanted to scroll the page down to the new element, but that didn't work for obvious reasons (bubbling, etc.). I came up with a simple fix...
So every time you add a fieldset, jQuery finds the last one added, then
.offset().top
measures how many pixels the fieldset is from the top and then scrolls the window that distance.you should specify a height for your div with overflow equals to auto :
Simple and easy way to listen to scroll event on dynamic loaded content