Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
661 views
in Technique[技术] by (71.8m points)

jquery - Bind scroll Event To Dynamic DIV?

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.

DEMO

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

$("body").on("custom-scroll", ".myDiv", function(){
    console.log("Scrolled :P");
})

$("#btn").on("click", function(){
    $("body").append('<div class="myDiv"><br><br><p>Content1<p><br><br><p>Content2<p><br><br></div>');
    listenForScrollEvent($(".myDiv"));
});


function listenForScrollEvent(el){
    el.on("scroll", function(){
        el.trigger("custom-scroll");
    })
}
body{ font-family: tahoma; font-size: 12px; }

.myDiv{
height: 90px;
width: 300px;
border: 1px solid;
background-color: lavender;
overflow: auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<input type="button" id="btn" value="Click"/>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...