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:
<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:
$(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 {
}
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.
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,
function () {
$that.ShowLoadingImange();
$that.data("ajax", true);
},
function (dt) {
$("#divNews").append(dt.d);
if (data.data != '') {
$(hdfPageIndex).val(pageIndex);
}
$that.data("ajax", false);
$that.find(".indicator").remove();
},
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.
<script type="text/javascript" src="Scripts/CommonFunctions.js"></script>
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).
[System.Web.Services.WebMethod]
public static string FetchNews(int pageIndex)
{
var sbToReturn = new StringBuilder();
var lstFetchSocialNews = lstSocialNewsRepository.Skip((pageIndex - 1) * PageSize).Take(PageSize).ToList();
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 .
</a><a href='#'>Comment .
</a><a href='#'>Share </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.
$.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