9

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

InOrderToLive
  • 186
  • 1
  • 1
  • 9

9 Answers9

14

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"/>
Bikal Basnet
  • 1,639
  • 1
  • 21
  • 31
2

I'm having the same issue and I've found the following in the jQuery .on() API:

In all browsers, the load, scroll, and error events (e.g., on an element) do not bubble. In Internet Explorer 8 and lower, the paste and reset events do not bubble. Such events are not supported for use with delegation, but they can be used when the event handler is directly attached to the element generating the event.

So unfortunately this doesn't appear to be possible.

Community
  • 1
  • 1
Nick Brunt
  • 9,533
  • 10
  • 54
  • 83
0

try this modified from your code

http://jsfiddle.net/apDBE/

$(document).ready(function(){

    // Trigger
    $("#btn").click(function(){
        if ($(".myDiv").length == 0) // Append once
        $("body").append('<div class="myDiv"><br><br><p>Content1<p><br><br><p>Content2<p><br><br></div>');
    });

    // Not working
    $(".myDiv").scroll(function(){
        alert("A");
    });

    // Not working
    $(document).on("scroll", ".myDiv", function(){
        alert("A");
    });
});

Hope this help

xicond
  • 19
  • 7
  • I'm unsure why you marked your first attempt as 'Not working', but I have updated your fiddle and it does seem to work: [updated fiddle](http://jsfiddle.net/rkLta3jg/1/), I've tested this in the latest versions of Safari, Chrome and Firefox at the time of writing. – olger Sep 18 '15 at 08:35
0

http://jsfiddle.net/hainawa/cruut/

$(document).ready(function(){
    var $mydiv = $('<div class="myDiv"><br><br><p>Content1<p><br><br><p>Content2<p><br><br></div>');

    // It will work
    $mydiv.scroll(function(){
        alert("A");
    });

    // Trigger
    $("#btn").click(function(){
        //You are using the method append,so you don't need judge if div.mydiv exits.
        //You'll need do this if you're using display:none
        $("body").append($mydiv);
    });
});
Daidai
  • 547
  • 4
  • 13
0

It's work by attaching on directly, check example bellow.

Hope this helps.

$("body").append('<div class="myDiv"><br><br><p>Content1<p><br><br><p>Content2<p><br><br></div>');

$(".myDiv").on("scroll", function(){
    console.log("scrolling");
}); 
 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.1/jquery.min.js"></script>
Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
0

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...

function scroll(pixels){
    $('html, body').animate({
        scrollTop: pixels
    }, 1000);
};

function addObservation(x){
    $('body').append(x);
    newFieldSet = $('fieldset').last();
    pixelsFromTop = newFieldSet.offset().top;
    scroll(pixelsFromTop);
};

$(document).on("click", "#add_observation", function(){
    addObservation("<fieldset>SOME FORM FIELDS HERE</fieldset>");
});

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.

skwidbreth
  • 7,888
  • 11
  • 58
  • 105
0

Simple and easy way to listen to scroll event on dynamic loaded content

<div class="scrollDiv" onscroll="LoadHistory()>
...Your contents to scroll goes here
</div>


</script type="text/javascript">

function LoadHistory(){
var pos = $(".scrollDiv").scrollTop();
if (pos == 0) {
  // your code goes in here
}
}
</script>
Bangash
  • 117
  • 9
-1

you should specify a height for your div with overflow equals to auto :

    .myDiv{
    height: 90px;
    overflow: auto;
}
hanane
  • 64
  • 1
  • 9
-3

element must be exists in document before you use jquey.on().

you can insert dummy <div class="mydiv"></div> before you use jquery.on()

$('body').append('<div class="mydiv" style="display:none"></div>');
$(document).on("scroll", ".mydiv", function(){...})
ketan
  • 390
  • 3
  • 6
  • Are you sure ? I don't agree with that. When using $(document).on(event, selector, function(){...}) The selector dont need to be existent. The document will bind it when it appears. You're breaking on's function. As your example, why dont we use: $(".mydiv").scroll(function(){...}) ? – InOrderToLive May 12 '13 at 09:18