Andrius Naruševičius
Andrius Naruševičius

Reputation: 8578

Proper way of binding an event of scroll in jquery

I have a simple piece of code and I am struggling to figure out why my scroll event isn't getting bound. This is a codepen link and I will post the code here too:

HTML:

<div class="aaa"></div>

CSS:

div.xxx
{
    height:100px;
    overflow:scroll;
    width:100px;
}

Javascript (jquery included):

$("*").on("scroll", function (event)
{
    alert("scrolled!");
    console.log("scroll");
});

$(document).ready(function() 
{
    $(".aaa").html('<div class="xxx">this<br/>this<br/>this<br/>this<br/>this<br/>this<br/>this<br/>this<br/>this<br/>this<br/>this<br/>this<br/>this<br/>this<br/>this<br/>this<br/>this<br/>this<br/>this<br/>this<br/>this<br/>this<br/>this<br/>this<br/></div>');     
});

What I want to do is to fire any scroll event (well, specifically the scroll in div.xxx) however if I make it so the code is loaded dynamically, it is not working.

P.S. I tried using live too, but apparently it is outdated and doesn't even support live. So I am out of choices.

P.S. I updated my codepen example to show that click event works, while scroll one doesn't even though they are written in the same way.

Upvotes: 0

Views: 4163

Answers (2)

Matyas
Matyas

Reputation: 13702

The problem with your code is that you assign the listener at the start of the application, and the listener assignments run once, and are assigned to every element they find and that's it.

Only after this phase you actually add your div, that is not listened to.

The solution is to add the listener after you add your new content.

To do this you should use something similar to the following javascript

// declare a listener method, don't assign it yet to any element
var scrolled = function (event) {
  // just a nicer way of notification (instead of alert)
  var s = $('.scroll');
  s.fadeIn(500, function(){
    s.fadeOut(200);
  });
};

$(document).ready(function() {   
    // element used to notify the user of scroll
    $('body').append('<div class="scroll" style="display: none">scrolled</div>');
    $(".aaa").html('<div class="xxx">this<br/>this<br/>this<br/>this<br/>this<br/>this<br/>this<br/>this<br/>this<br/>this<br/>this<br/>this<br/>this<br/>this<br/>this<br/>this<br/>this<br/>this<br/>this<br/>this<br/>this<br/>this<br/>this<br/>this<br/></div>')
             .children('.xxx') // select the newly added container
             .on("scroll", scrolled); // add the method above as a scroll listener
});

This way you add the scroll listener every time you add fresh content. So the new divs will be listened to.

Working example

Upvotes: 2

Eli
Eli

Reputation: 14827

Change:

div.xxx
{
    height:100px;
    overflow:scroll;
    width:100px;
}

to:

div.aaa
{
    height:100px;
    overflow:scroll;
    width:100px;
}

There is no div with class xxx

Updated Demo

Upvotes: 0

Related Questions