Wednesday, November 21, 2012

Auto increase content on scrolling

Hi,

I recently got script request for developing something which has become very common in most websites. Mostly seen in sites like Facebook. For any given container in a web page, which has a scroll bar, when the user reaches the end of the scroll height, the content of that container auto populates itself. This article covers this functionality.

Lets see few screen shots to better understand the concept:


1. Normal div with sample content and a scroll bar

2. User reaches the end of scroll

3. Immediately the content of the div increases


Download: autoScrollContent.zip

Explanation:


The sample uses a generic jQuery package just to make our lives easier. I have added script.js file which does the job. Now lets have a look at each functions I have used in details.


First I am using two global javascript variables
var maxScrollHeight; // used to store the max scroll allowed for the container
var initDiv;  // ID of the container.

Initialising the variables
This function is used to initialise the container ID and getting the initial max scroll amount

function init(did){
    initDiv=did;
    getMaxHeight();
    jQuery('#' + initDiv).scroll(function(){
        if(maxScrollHeight==jQuery('#' + initDiv).scrollTop() && maxScrollHeight<1500){
            increaseContent()
        }
    })
}

In the above sample:

jQuery('#' + initDiv).scroll(function(){
        if(maxScrollHeight==jQuery('#' + initDiv).scrollTop() && maxScrollHeight<1500){
            increaseContent()
        }
    })

this code is used to check whether the scrolling has reached its maximum limit. If so then the content is increased using the increaseContent() function. Now this is the function you might need to customize for making Ajax calls or whatever.

Getting the allowed scrollable value
This gets the max scrolling any one can do for a particular container.

function getMaxHeight(){
    maxScrollHeight=document.getElementById(initDiv).scrollHeight - parseInt(jQuery('#' + initDiv).css("height"));
}

Now putting it all together:
In my HTML page I create a div and call the init() function and everything falls in place:

<div id="container" style="width: 300px;height:400px;overflow-y:auto">
   ..............................     
</div>

<script>
        jQuery(document).ready(function(){
            init('container');
        })
</script>

Download example: autoScrollContent.zip

Hope this helps!!!

1 comment:

  1. Really Good Article and very useful. :)

    ReplyDelete