Click here to Skip to main content
15,887,214 members
Articles / Web Development / ASP.NET
Tip/Trick

Show More Data When Mouse Scrolling Down

Rate me:
Please Sign up or sign in to vote.
4.68/5 (12 votes)
21 Feb 2014CPOL1 min read 20.1K   578   22   2
Show more data when window scrolling down like Facebook, Twitter...

Introduction

Almost all social webpages like Facebook, Twitter, Google+..., display the latest news, status on the top, then you scroll down to the bottom, it automatically shows older data. In this tip, I am going to show you a sample of loading more on event mouse scrolling down using jQuery and ASP.NET C#.

Using the Code

In the head section (head tag), you need to refer to jQuery library like below:

JavaScript
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script> 

And on ready function, you should code like this. In the below code, there is an event $(document).scroll() to detect window scrolling event:

JavaScript
$(function () {
           doLoadingMore($("#divNews"), 1);
           $(document).unbind("scroll");
           var lastScrollTop = 0;
           $(document).scroll(function (event) {
               var st = $(this).scrollTop();
               if (st > lastScrollTop) {
                   if (st >= ($(document).height() - $(window).height())) {
                       doLoadingMore($("#divNews"), 0);
                   } else {
                       //donothing
                   }
                   lastScrollTop = st;
               }
           });

 });

The doLoadingMore function should be like below. In this code block, there is a hidden field to update the page index value when data loaded.

JavaScript
function doLoadingMore(that, actiontype) {
           var $that = $(that);
           if ($that.data("ajax") == true)
               return;
           var hdfPageIndex = $("#<%=hdf_page_index.ClientID %>");
           var pageIndex = parseInt($(hdfPageIndex).val());
           if (actiontype == 1) {
               pageIndex = 1;
               $(hdfPageIndex).val("1");
           } else {
               pageIndex = parseInt(pageIndex) + 1;
           }
           var data = "{'pageIndex':'" + pageIndex + "'}";
           LoadingAjax("jQueryShowMore.aspx/FetchNews", data,
           //Before send
               function () {
                   $that.ShowLoadingImange();
                   $that.data("ajax", true);
               },
           //On success
               function (dt) {
                   $("#divNews").append(dt.d);
                   if (data.data != '') {
                       $(hdfPageIndex).val(pageIndex);
                   }
                   $that.data("ajax", false);
                   $that.find(".indicator").remove();
               },
           //On error
               function () {
                   $that.data("ajax", false);
                   $that.find(".indicator").remove();
               }
           );
       }

The LoadingAjax function is defined in CommonFunctions.js file. You should refer to it. This function is used to call a service method and return data as json formatted.

JavaScript
<script type="text/javascript" src="Scripts/CommonFunctions.js"></script>

JavaScript
var base_ajax_timeout = 120000;
function LoadingAjax(url, datapost, beforesend, onsuccess, onerror) {
    $.ajax({
        url: url,
        data: datapost,
        dataType: 'json',
        contentType: 'application/json; charset=utf-8',
        type: 'POST',
        async: true,
        timeout: base_ajax_timeout,
        beforeSend: function () {
            beforesend();
        },
        success: function (data) {
            if (data.d != null) {
                onsuccess(data);
            }
        },
        error: function () {
            onerror();
        }
    });
} 

In the jQueryShowMore.aspx.cs file, there is a service method called FetchNews to load data from repository (like database, but in this example, the data is stored in heap memory).

C#
[System.Web.Services.WebMethod]
       public static string FetchNews(int pageIndex)
       {
           var sbToReturn = new StringBuilder();
           var lstFetchSocialNews = lstSocialNewsRepository.Skip((pageIndex - 1) * PageSize).Take(PageSize).ToList();
           //Server delay to see loading image
           System.Threading.Thread.Sleep(1200);
           foreach (var item in lstFetchSocialNews)
           {
               string imagePath = (item.ImagePath != "") ? "<tr>
               <td><img src='{3}' id='imageContent'/></td></tr>" : "{3}";
               sbToReturn.AppendFormat("<div id='container'>" +
                                       "<table>" +
                                       "<tr>" +
                                       "<td rowspan='4' valign='top'>" +
                                       "<img src='{0}' id='avatar'/>" +
                                       "</td>" +
                                       "<td id='owner'>" +
                                       "<b>{1}<b>" +
                                       "</td>" +
                                       "</tr>" +
                                       "<tr>" +
                                       "<td id='contentText'>" +
                                       "{2}" +
                                       "</td>" +
                                       "</tr>" +
                                       imagePath +
                                       "<tr>" +
                                       "<td style='font-size:0.8em;'>
                                       <a href='#'>Like&nbsp;&nbsp;&nbsp;.
                                       </a><a href='#'>Comment&nbsp;&nbsp;&nbsp;.
                                       </a><a href='#'>Share&nbsp;&nbsp;&nbsp;</a>" +
                                       "<span id='postedDate'>{4}</span>" +
                                       "</td>" +
                                       "</tr>" +
                                       "</table>" +
                                       "</div>", item.AvatarPath, item.Owner, item.ContentText, item.ImagePath,
                                       item.PostedDate);
           }
           return sbToReturn.ToString();
       }

The ShowLoadingImage function is a user function defined in $.fn.extend like below. It displays the loading image when waiting for response from the server.

JavaScript
$.fn.extend({
    ShowLoadingImange: function () {
        var img = $(this);
        $(this).css({ "position": "relative" });
        var indicator = $("<div>").addClass("indicator").css({
            width: img.width(),
            height: img.height(),
            backgroundColor: "#ffffff",
            opacity: 0.3,
            display: "block",
            position: "absolute",
            top: 0,
            'z-index': 9999
        }).append($("<img>", {
            src: "Images/indicator.gif"
        }).css({
            position: "fixed",
            top: $(window).innerHeight() / 2,
            left: $(window).innerHeight() / 2 + 300
        }));
        return $(this).append(indicator);
    }
});

Points of Interest

Loading more data on window scrolling instead of using paging.

History

  • 21st February, 2014: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
Vietnam Vietnam
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralMy vote of 5 Pin
Humayun Kabir Mamun23-Feb-14 19:32
Humayun Kabir Mamun23-Feb-14 19:32 
GeneralRe: My vote of 5 Pin
sieunhantanbao24-Feb-14 14:35
sieunhantanbao24-Feb-14 14:35 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.