Infinite scroll loading for div element
This article explains how to incrementally load items as you scroll down div element in the page. In this example a HTML page is created with an unordered list element where the list items returned by the function gets appended. Here difference of the scroll height of the div container and its client height is compared against the scroll top offset value.
HTML Page<div> <div id="containerName" style="overflow: scroll;height: 500px;"></div><div style="text-align: center;"><img alt="Loading..." src="../assets/images/svg/three-dots.svg" class="loading-info" /></div><div id="notifyMessage"></div> </div>Jquery
$(document).ready(function () {var offset = 0;var loading = false;$('.loading-info').hide();appendItems(offset, loading);$(window).scroll(function () {if ($('#notifyMessage').html() === "") { var divHeight = $('#containerName')[0].scrollHeight - $('#containerName')[0].clientHeight;if ($('#containerName').scrollTop() === divHeight) {offset += 20; appendItems(offset, loading); } } });});
function appendItems(offset, loading) { if (loading == false) { loading = true; $('.loading-info').show(); $.post('/admin/items/append', { 'offset': offset }, function (data) { loading = false; if (data.trim().length == 0) { $('.loading-info').hide(); $('#notifyMessage').html('<p> End of records</p>'); return; } $('.loading-info').hide(); $("#containerName").append(data); }).fail(function (xhr, ajaxOptions, thrownError) { alert(thrownError); }) } }PHP Function
function append() { $list = NULL; $offset = $_POST['offset']; $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "myDB"; // Create connection $conn = new mysqli($servername, $username, $password, $dbname); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } $sql = "SELECT id, firstname, lastname FROM employees limit $offset, 20"; $result = $conn->query($sql); if ($result->num_rows > 0) { // output data of each row while($row = $result->fetch_assoc()) { $list += "<div>id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "</div>"; } } $conn->close(); echo $list; }
No comments:
Post a Comment