Rstew
Rstew

Reputation: 605

Jquery .on() Scroll not functioning on dynamic div

I have tried about every other "solution" that I have found on SO and on other parts of the web and still cannot get this to work.

I have a dynamically created div with position: fixed; overflow-y: auto, the div is created when a user clicks a certain link. This is the function I'm using to try and execute some code whenever that dynamically created div is scrolled.

        $("#scroller").on("scroll",function() {
           console.log("scrolled..");
        });

#scroller is the ID of the dynamically created div.

The thing is, this function does not work when the page is loaded, but it does work when the function is pasted into the developer console in Google Chrome.

I have tried everything from using a regular scroll() function to changing the on() function to the following:

    $("#scroller-container").on("scroll","#scroller",function() {
       console.log("scrolled..");
    });

Yet it still does not work.

How can I get this to work?

EDIT: All the code is within a jQuery(window).load(function ()... function

Upvotes: 0

Views: 353

Answers (1)

Shady Alset
Shady Alset

Reputation: 5714

Try binding scroll event after the element is appended on the DOM, like this:

$("body").on("DIVscroll", "#scroller", function(){
  console.log("Scrolled...");
});

$("#btn").on("click", function(){
  $("body").append('<div id="scroller">I have a dynamically created div with position: fixed; overflow-y: auto, the div is created when a user clicks a certain link. This is the function Im using to try and execute some code whenever that dynamically created div is scrolled.</div>');
  ScrollEventListener($("#scroller"));
});

function ScrollEventListener(el){
  el.on("scroll", function(){
    el.trigger("DIVscroll");
  });
}
body{
  font-size: 17px;
}
	
#scroller{
  height: 100px;
  width: 300px;
  border: 1px solid;
  overflow-y: auto;
  position: fixed;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" id="btn" value="Append div"/>

Upvotes: 2

Related Questions