sultan sultan - 12 days ago 6
CSS Question

JQuery: scroll event doesn't work

I've been trying to bind scroll event to an element on the page. And on scroll load more content like twitter or facebook do.

HTML



<div id="main-content">
<ul class="event-list big row" id="event-list">
...
</ul>
</div>


CSS



#main-content {
width: 984px;
overflow: visible;
margin: 0 auto;
color: #101010;
width: 974px;
padding: 10px 0 7px 0;
}
#main-content .event-list.big {
width: 1080px;
padding: 0 0 20px 0;
}


JS code



$('#event-list').scroll(function() {
var curScroll = $(this)[0].scrollTop,
maxScroll = $(this)[0].scrollHeight - $(this).height();

console.log(curScroll, ' :: ', maxScroll);

if ((curScroll >= maxScroll - 200) && !loading) {
loading = true;

$(this)[0].scrollTop = curScroll;

$('.loading').fadeIn('fast');

if (page <= $('.page').length) {
loadMore();
}
}
});


scroll event is not triggered when I scroll its even don't print out curScroll and maxScroll.

What may cause the problem at all, may be css styles are wrong or my js code wrong?

Answer

Here's a working example of what I believe you want with the scrolling event triggering. Use the div as a scrollable region by setting 'overflow: scroll'. Note: you will only get the scroll event if the list is long enough on the initial load. (See the height property on main-content. I'll leave the ajax loading up to you. :)

CSS

 #main-content {
    width: 984px;
    overflow: scroll;
    margin: 0 auto;
    color: #101010;
    width: 974px;
    height: 100px;
    padding: 10px 0 7px 0;
}
#main-content .event-list.big {
   width: 1080px;
   padding: 0 0 20px 0;
}

Script

$(document).ready(function() {
            $('#main-content').scroll(function() {
              var curScroll = $(this)[0].scrollTop,
                  maxScroll = $(this)[0].scrollHeight - $(this).height();

              console.log(curScroll, ' :: ', maxScroll);

              if ((curScroll >= maxScroll - 200) && !loading) {
                  loading = true;

                  $(this)[0].scrollTop = curScroll;

                  $('.loading').fadeIn('fast');

                  if (page <= $('.page').length) {
                      loadMore();
                  }
              }
            });
        });

HTML

<div id="main-content">
    <ul class="eventlist big row" id="event-list">
      <li>1</li>
      <li>2</li>
      <li>3</li>
      <li>4</li>
      <li>5</li>
      <li>6</li>
      <li>7</li>
      <li>8</li>
      <li>9</li>
      <li>0</li>
      <li>1</li>
      <li>2</li>
      <li>3</li>
      <li>4</li>
      <li>5</li>
    </ul>
</div>