Rectangle 27 1

If anyone is looking to implement infinite scroll on WordPress, use Wataru's Infinite Scroll with URL cycling Script

Download the script, enqueue it in the footer or concatenate it with gulp or however you choose to use it.

How to implement infinite scroll in WordPress:

<?php get_header(); ?>

   <main id="post-left-col" class="relative infinite-container" role="main">

      <?php if (have_posts()) : while (have_posts()) : the_post();

                    get_template_part( 'template-parts/post/content' );

                endwhile; endif;
                 ?>
                </main>
        </div>
<?php get_footer(); ?>
<?php
    /**
     * Template part for displaying posts
    */
    ?>
    <article id="post-area" class="infinite-post">

<!-- Insert your post format here e.g. <h1><?php the_title; ?></h1> etc..
<div class="navigation"><?php next_post_link(); ?></div>

at the end of your content.php post template.

2) Set up your infinite scroll configuration. This, of course, can be included in your main javascript file. Any of the below selectors can have their name changed.

jQuery(document).ready(function($) {

    $('.infinite-content').cleverInfiniteScroll({
                contentsWrapperSelector: '.infinite-container',
                contentSelector: '.infinite-post',
                nextSelector: '.navigation a:first'
            });
});

Thanks to Paul Irish and Wataru for building upon the infinite scroll script.

jquery - How can I make wordpress infinite scrolling change the URL? -...

jquery wordpress infinite-scroll html5-history
Rectangle 27 3

You can look into jquery's infinite scroll:

Which sounds like it does what you're asking for, assuming you're willing to use the jquery library and not hoping for a strict pure JS method.

While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes.

@Hatsjoem He's linking to a plugin. What exactly are the "essential parts" that should be copied over? Who cares if the answer "becomes invalid if the linked page changes"? If the link becomes broken, that means the plugin was discontinued and doesn't exist anymore - even if you add more info to the answer, it would still be invalid. Jeez, link-only answers aren't necessarily bad.

@Hatsjoem Also, from meta: "When the library referenced is at a well-known, stable location, this kind of answer is a generally poor answer but an answer nonetheless: it says use this."

Plus, google will probably still exist if infinite scroll changes this URL. The point is to use that plugin so if the link dies, just google search jquery infinite scroll. You'll probably find what you need.

Javascript: How to detect if browser window is scrolled to bottom? - S...

javascript
Rectangle 27 3

You can look into jquery's infinite scroll:

Which sounds like it does what you're asking for, assuming you're willing to use the jquery library and not hoping for a strict pure JS method.

While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes.

@Hatsjoem He's linking to a plugin. What exactly are the "essential parts" that should be copied over? Who cares if the answer "becomes invalid if the linked page changes"? If the link becomes broken, that means the plugin was discontinued and doesn't exist anymore - even if you add more info to the answer, it would still be invalid. Jeez, link-only answers aren't necessarily bad.

@Hatsjoem Also, from meta: "When the library referenced is at a well-known, stable location, this kind of answer is a generally poor answer but an answer nonetheless: it says use this."

Plus, google will probably still exist if infinite scroll changes this URL. The point is to use that plugin so if the link dies, just google search jquery infinite scroll. You'll probably find what you need.

Javascript: How to detect if browser window is scrolled to bottom? - S...

javascript
Rectangle 27 7

Here's what I put together from the info provided... works with the mousewheel, swiping and clicking on the top and bottom numbers. Infinite as requested of course. No special perspective style (yet) but I thought it looked quite decent as is. Could still be an option naturally. Didn't use the plugin I linked to in the comments or requestAnimationFrame but jQuery animate() is quite a good tool for this. The library has great cross browser support (that's it's strength actually), all it needs is a link to it for the JavaScript to be able to get executed. You could use a CDN, this version also works for IE8- :

For the best cross browser support on using the mousewheel, this plugin was included :

<script src="//cdnjs.cloudflare.com/ajax/libs/jquery-mousewheel/3.1.12/jquery.mousewheel.js"></script>

Just a basic parent and styling with spans for each number, a few prepended in case of going up.

$(function() {

var gate = $(window),
cog = $('#rotator'),
digit = cog.find('span'),
slot = digit.eq(0).height(),
base = 1.5*slot,
output = $('#result'),
up;

cog.fadeTo(0,0);

gate.on('load', function() {

	setTimeout(interAction, 50);
});

function interAction() {

	output.text(0);

	cog.scrollTop(base).fadeTo(0,1).mousewheel(function(turn, delta) {

		if (isBusy()) return false;

		delta < 0 ? up = true : up = false;

		newNumber();

		return false;
	});

	digit.on('touchstart', function(e) {

		var touch = e.originalEvent.touches,
		begin = touch[0].pageY, swipe;

		digit.on('touchmove', function(e) {

			var contact = e.originalEvent.touches,
			end = contact[0].pageY,
			distance = end-begin;

			if (isBusy()) return;

			if (Math.abs(distance) > 30) {
			swipe = true;
			distance > 30 ? up = true : up = false;
			}
		})
		.add(gate).one('touchend', function() {

			if (swipe) {
			swipe = false;
			newNumber();
			}

			digit.off('touchmove').add(gate).off('touchend');
		});
	})
	.on('mousedown touchstart', function(e) {

		if (e.which && e.which != 1) return;

		var item = $(this).index();

		if (item == 1 || item == 3) {

		digit.one('mouseup touchend', function() {

			var same = item == $(this).index();

			if (isBusy() || !same) return cancelIt();

			item == 1 ? up = true : up = false;

			newNumber();

			return cancelIt();
		});
		}

		return false;
	});
}

function isBusy() {

	return cog.is(':animated');
}

function cancelIt() {

	digit.off('mouseup touchend');

	return false;
}

function newNumber() {

	var aim = base;

	up ? aim -= slot : aim += slot;

	cog.animate({scrollTop: aim}, 250, function() {

		up ? digit.eq(9).prependTo(cog) : digit.eq(0).appendTo(cog);

		cog.scrollTop(base);

		digit = cog.find('span');

		output.text(digit.eq(2).text());
	});
}
});
body {
  font-family: "Times New Roman";
  background: grey;
}

#ticker {
  width: 150px;
  text-align: center;
  margin: auto;
}

#rotator {
  height: 140px;
  background-image: url(//i.imgsafe.org/2d8949191f.png);
  background-size: 100% 100%;
  margin: 0 0 10px;
  overflow: hidden;
}

#rotator span {
  width: 100%;
  height: 50%;
  display: inline-block;
  font-size: 50px;
  line-height: 70px;
  cursor: default;
}

#result {
  height: 30px;
  font-size: 20px;
  color: white;
  line-height: 30px;
  box-shadow: 0 0 3px black;
}
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery-mousewheel/3.1.12/jquery.mousewheel.js"></script>

<div id="ticker">
 <div id="rotator">
   <span>8</span>
   <span>9</span>
   <span>0</span>
   <span>1</span>
   <span>2</span>
   <span>3</span>
   <span>4</span>
   <span>5</span>
   <span>6</span>
   <span>7</span>
 </div>
 <div id="result"></div>
</div>

Pretty straightforward, animates the scroll position up or down and then appends or prepends the first or last number depending on the direction. The duration of the animation can be set here :

cog.animate({scrollTop: current}, 250, function() {

Updated - now has swipe support for mobile devices (even tested on early Android), the mousewheel plugin instead of relying on the wheel event and added a div where count is kept. Plus minor tweaks.

Meanwhile I've also made a demo that allows to have multiple tickers. It can be found here :

Thats amazing! Its working really well! The touchstart seems to be very fast/responsive , Im really curious to see how it would look with swipe support on my phone and tablet, would it be possible to add this to your example as well if its not too much trouble?

Im not sure what the wheel event is, would its effect look much different than what youve currently made? If its a relatively new thing does that mean that older browsers wouldnt be able to use it? Ideally Id like the method used to move the wheel to be widely supported across all browsers and devices, and to keep being supported going into the future.

I was wondering, with your example, is it possible to grab the selected number and send it to my database? By this I mean that Id like to have a div below the wheel which contains a button that when pressed will send the selected number to my database by an ajax post linked to a php script. In the first example in my question the selected number was called currentPosition, and it was placed inside the div called value here: currentPosition = targetPosition; document.getElementById("value").innerHTML = "Value: " + currentPosition;...

the number appearing in this div ("value") would change automatically whenever the wheel was moved. Im able to send the contents of this div to my database on click of a submit button, but I was wondering what the equivalent of currentPosition is in your code? Thanks so much again for your help, it looks great!

Looked at it closely and think all requirements are incorporated in the update... but been tweaking it a bit since I posted that. I may need to make another edit to the answer but I'll do that when there's nothing left to be changed. I'd really like to leave a good script here but don't wanna overdo it either.

javascript - How to make a HTML5 spinning list/rotating wheel selector...

javascript html css html5 animation
Rectangle 27 0

Use server side processing where JQuery DatraTables send new ajax requests for each new page. Maybe you can also use infinite scrolling. Configuration shoudl look like:

$('#example').dataTable( {
    "bServerSide": true,
    "sAjaxSource": "../server_side/scripts/server_processing.php"
    sScorollX: "300px", 
    sScrollY: "200px"
    bScrollInfinite:true //this property disables pagination
} );

You can find more details on the DataTables site.

jQuery DataTables staggered loading - Stack Overflow

jquery datatables
Rectangle 27 0

You can easily remove you old pagination and enjoy the infinite scroll functionality by using this jquery plugin

javascript - Implementing Infinite Scrolling with jquery - Stack Over...

javascript jquery jquery-masonry infinite-scroll
Rectangle 27 0

You can not use animate() method with scroll function it will create conflict because scroll value will change always and jQuery can not infinite repeat same animation. Stop won't rescue this issue either, or i cound't manage to do it.

if
$(window).scroll(function() {
    var scrollVal = $(this).scrollTop();
    if ( scrollVal > offset.top) {
        $sidebar.css({
           'margin-top': (($window.scrollTop() - offset.top) + topPadding) + 'px'
                       //added +'px' here to prevent old internet explorer bugs
        });
    } else {
        $sidebar.css({'margin-top':'0px'});
    }
});

Note: if you want to expand your if statements with else if, don't use else, it will create conflict too. Bealive me i am really expreienced with this issue.

You can change your approuch to calculations of the limits too. I presume you want to fix the nav and your html is like this:

<div class="wrapper">
    <div class="header">header</div>
    <span id="subnav">hold this</span>
</div>

and jQuery calculations should be like this: Here is working jsFiddle.

$(document).ready(function() {
   $(window).scroll(function() {
       var headerH = $('.header').outerHeight(true);
      //this will calculate header's full height, with borders, margins, paddings
       console.log(headerH);
       var scrollVal = $(this).scrollTop();
        if ( scrollVal > headerH ) {
        //when scroll value reach to your selector
            $('#subnav').css({'position':'fixed','top' :'0px'});
        } else {
            $('#subnav').css({'position':'static','top':'0px'});
        }
    });
 });

Now it does nothing. I feel it's because there is a variable issue. Ideas?

You got problems with calculations too mate, i updated my answer.

jquery - Setting CSS value limits of the window scrolling animation - ...

jquery html css scroll sticky
Rectangle 27 0

You don't even need a plugin to accomplish this. This is done with some simple lines of jQuery:

$("a").live("click", function(){
    var data = "<li style='display:none'>Text3</li>";

    $("ul").append(data);
    $("li:hidden").fadeIn('slow');
});

data might be anything (just be sure it is invisible to have the fade effect and you need to edit the li:hidden). E.g. it could be the result of an ajax request. Depending on the type of result (e.g. html or json) you would need to prepare it to make it fit into your html.

If you have trouble with your ajax response please post the code.

you are right. now i feel why i spent a lot's of time in this whenever i can write my own script. thanks a lot

jquery - How I can use infinite scrolling in the webpage where I want ...

jquery html design interaction infinite-scroll
Rectangle 27 0

I used Infinite scrolling JQuery plugin and it is just working fine. This jquery plugin will give you custom built-in events that you can use to send Ajax request to your controller's method. Also if it will be working then you can change it css to looks like facebook infinite scrolling functionality.

Here is another post that will help you how to use it with CakePHP.

I think you didn't get my point. I want to load data and fetch as well when button is clicked I don't wish to fetch all at once and then show in chucks...I wish to trigger query only when button is clicked and then append that data..

Rahul the above post is same as you are requiring. This Jquery plugin will help you to fetch the data in a blocks not all at once. Thats why you this gives you ajax send event. You might have to customize it like on the button click you need more results. Try to read the documentation of this plugin. It works well.

I m still bit confused with Implementation. I mean on my view. $('<div/>').load('Controller/action/page:2/ #content div.post',function(){ $(this).appendTo('#content'); }); N in my controller I use to check if request ajax than render some view. Having loop of next posts.. Means I have to render element. Right..

Yes you'll have to render your element. You can also use $.ajax() function instead of load() function to send ajax request to the controller's method and render your element in that controller's action.

cakephp 2.0 - Ajax Pagination append the element instead of updating i...

cakephp-2.0
Rectangle 27 0

If you want to use infinite scrolling , means on page load some content are pre load and then user scroll down and other content are load on scroll with lazy loging, if i am understan right then please try to use jscroll jquery plugin.. it's very good for infinite scroll. http://jscroll.com/ you can find here document and example of this plugin.

Thanks Vinit, lemme have a look at it once

ok if you need to more guide line in jscroll then tell me i am here..have a good day

iscroll - iScroll5 Infinite scrolling - lazy loading - Stack Overflow

lazy-loading iscroll android-lazyloading
Rectangle 27 0

You can have many options for your search. My suggestion would be using infinite scroll with ajax search and range selector. As per your request choosing multiple brands in the leftsidebar and then setting the range for products will be achieved by joining some of the jquery plugins.

There are many options you can choose from some links are listed below you can refer them.

Not exactly what I wanted but all the same it's most welcome, I can research these more and implement where needed in future websites, thank you. Except for the product search php mysql, I already have that :)

PHP MySql E-Commerce left column filter results - Stack Overflow

php mysql filter
Rectangle 27 0

There are many jquery plugins that can be used for using infinite scroll effect with pagination. you can use following plugins.

javascript - How to Load More JSON Data when scrolling page to bottom?...

javascript jquery ajax json scroll
Rectangle 27 0

You need to add an event listener using JavaScript, means when a particular element comes to view port an event is fired and it fetches the data from some external resources. The data comes in JSON and you need to extract it and append the info in a DIV. For this I have made a script which fetches the data from Google Docs using Jquery and the event is fired after you scroll to the bottom most portion. You can check the infinite scroll here

How do you make an infinite scroll page in Blogger? - Stack Overflow

blogger infinite-scroll
Rectangle 27 0

You can use jQuery Waypoints Infinite Scroll Plugin

$('.infinite-container').waypoint('infinite', {
  container: 'auto',
  items: '.infinite-item',
  more: '.infinite-more-link',
  offset: 'bottom-in-view',
  loadingClass: 'infinite-loading',
  onBeforePageLoad: $.noop,
  onAfterPageLoad: $.noop
});

asp.net mvc 4 - Load page when ever cursor reach page end in mvc 4 usi...

jquery asp.net-mvc-4 jquery-mobile
Rectangle 27 -1

After along day, i have implemented a smooth infinite scroll and pull to refresh sample app using iscroll4. these two functionality were implemented in one sample app i created. hope its useful to this mobile app developer community.

  • you are familiar with iscroll4 functions (Not much of a necessity cos am not a guru either).
  • you know how to make ajax calls to a json file or json/php file

Problem nature: i want infinite scrolling alongside pull to refresh functions and i dont want to use any other framework apart from iscroll4.

<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<link href="http://fonts.googleapis.com/css?family=Headland+One%7COpen+Sans:400,300&amp;subset=latin,cyrillic" rel="stylesheet" type="text/css"></link>
  <link href="css/mystylesheet.css" rel="stylesheet">
<style>

/**
 *
 * Horizontal Scrollbar
 *
 */
.myScrollbarH {
    position:absolute;
    z-index:100;
    height:8px;
    bottom:1px;
    left:2px;
    right:7px
}

.myScrollbarH > div {
    position:absolute;
    z-index:100;
    height:100%;

    /* The following is probably what you want to customize */
    background:-webkit-gradient(linear, 0 0, 100% 0, from(#226BF4), to(#226B8F));
    background-image:-moz-linear-gradient(top, #226BF4, #226B8F);
    background-image:-o-linear-gradient(top, #226BF4, #226B8F);

    border:1px solid #226BF4;

    -webkit-background-clip:padding-box;
    -moz-background-clip:padding-box;
    -o-background-clip:padding-box;
    background-clip:padding-box;

    -webkit-box-sizing:border-box;
    -moz-box-sizing:border-box;
    -o-box-sizing:border-box;
    box-sizing:border-box;

    -webkit-border-radius:4px;
    -moz-border-radius:4px;
    -o-border-radius:4px;
    border-radius:4px;

    -webkit-box-shadow:inset 1px 1px 0 rgba(255,255,255,0.5);
    -moz-box-shadow:inset 1px 1px 0 rgba(255,255,255,0.5);
    -o-box-shadow:inset 1px 1px 0 rgba(255,255,255,0.5);
    box-shadow:inset 1px 1px 0 rgba(255,255,255,0.5);
}


/**
 *
 * Vertical Scrollbar
 *
 */
.myScrollbarV {
    position:absolute;
    z-index:100;
    width:8px;bottom:7px;top:2px;right:1px
}

.myScrollbarV > div {
    position:absolute;
    z-index:100;
    width:100%;

    /* The following is probably what you want to customize */
    background:-webkit-gradient(linear, 0 0, 100% 0, from(#226BF4), to(#226B8F));
    background-image:-moz-linear-gradient(top, #226BF4, #226B8F);
    background-image:-o-linear-gradient(top, #226BF4, #226B8F);

    border:1px solid #226BF4;

    -webkit-background-clip:padding-box;
    -moz-background-clip:padding-box;
    -o-background-clip:padding-box;
    background-clip:padding-box;

    -webkit-box-sizing:border-box;
    -moz-box-sizing:border-box;
    -o-box-sizing:border-box;
    box-sizing:border-box;

    -webkit-border-radius:4px;
    -moz-border-radius:4px;
    -o-border-radius:4px;
    border-radius:4px;

    -webkit-box-shadow:inset 1px 1px 0 rgba(255,255,255,0.5);
    -moz-box-shadow:inset 1px 1px 0 rgba(255,255,255,0.5);
    -o-box-shadow:inset 1px 1px 0 rgba(255,255,255,0.5);
    box-shadow:inset 1px 1px 0 rgba(255,255,255,0.5);
}

/**
 *
 * Pull down styles
 *
 */
#pullDown, #pullUp {
    background:#fff;
    height:40px;
    line-height:40px;
    padding:5px 10px;
    border-bottom:1px solid #ccc;
    font-weight:bold;
    font-size:14px;
    color:#888;
}
#pullDown .pullDownIcon, #pullUp .pullUpIcon  {
    display:block; float:left;
    width:40px; height:40px;
    background:url(images/pull-icon@2x.png) 0 0 no-repeat;
    -webkit-background-size:40px 80px; background-size:40px 80px;
    -webkit-transition-property:-webkit-transform;
    -webkit-transition-duration:250ms;  
}
#pullDown .pullDownIcon {
    -webkit-transform:rotate(0deg) translateZ(0);
}
#pullUp .pullUpIcon  {
    -webkit-transform:rotate(-180deg) translateZ(0);
}

#pullDown.flip .pullDownIcon {
    -webkit-transform:rotate(-180deg) translateZ(0);
}

#pullUp.flip .pullUpIcon {
    -webkit-transform:rotate(0deg) translateZ(0);
}

#pullDown.loading .pullDownIcon, #pullUp.loading .pullUpIcon {
    background-position:0 100%;
    -webkit-transform:rotate(0deg) translateZ(0);
    -webkit-transition-duration:0ms;

    -webkit-animation-name:loading;
    -webkit-animation-duration:2s;
    -webkit-animation-iteration-count:infinite;
    -webkit-animation-timing-function:linear;
}

@-webkit-keyframes loading {
    from { -webkit-transform:rotate(0deg) translateZ(0); }
    to { -webkit-transform:rotate(360deg) translateZ(0); }
}

</style>
</head>
<body style="overflow: hidden;" onload="do_refresh();">
<div class="wrap">
<div id="wrapper">
        <div id="scroller">
        <div id="pullDown">
            <span class="pullDownIcon"></span><span class="pullDownLabel">Pull down to refresh...</span>
        </div>

    <div class="content">
    <input type="hidden" id="last_id">              
            <div id="responsecontainer"></div>
        </div>

        <span class="load_more_loading" ></span>
    </div>
    </div>
</div>


       <script type="text/javascript" src="js/jquery-1.9.1.min.js"></script>
        <script src="js/iscroll.js"></script>
<script src="js/pulltorefresh.js"></script>
<script src="js/infinitescroll.js></script>

<script src="js/myinitialloadscript.js"></script>
    <script src="js/mymobileframework.js"></script> <!--independent of this script. eg. whormhole from mosync-->

    </body>
        </html>

next is to create the myinitialloadscript.js script. this allows content to be loaded into the app for the first time on that page.

function do_refresh()
    {


    var url = "http://localhost/public_html/landing.php?token=908765789897867567687989089786768980&validator=jhjhjjhjhkhj"; //just url params
    // -------------------------------------------

    $.ajax({
            type: 'GET',
            url: url,
            contentType: "application/json; charset=utf-8",
            dataType: "jsonp",
            // Evaluate text as a json expression
            converters: {"text jsonp": jQuery.parseJSON},
            timeout:30000,
            async: true,
            jsonp: true,
            jsonpCallback: "myJsonMethod",
            beforeSend: function()
            {


//add loading image i dint bcos the image or values becomes double in a case of network delay
            $("#responsecontainer").html("images/loader.gif").show();
            },
            success: function(data)
            {
           ajax.parseJSONP(data);
            },
            error: function(jqXHR, textStatus, errorThrown)
            {
            console.log(errorThrown);
            alert("Could Not Refresh.");
            $("#responsecontainer").html("");//remove loading image
            //$("#responsecontainer").load("refresh_h.html"); //load a page with refresh option.
            }
        });
    $.ajaxSetup({ cache: false }); //fetch data from db not cache content
    }


//if data is fectched successfully then

    var ajax = {  

        parseJSONP:function(data){



            $.each(data, function(i, row) {
            if (i==0){
            $("#responsecontainer").html('');
            }

            var ul = '<li>'+row.myjsondatakey+'</li>'; //could be <div></div> This only displays your values from db in a styled manner
            $(ul).appendTo('#responsecontainer');// append the value to the responsecontainer

//Now watch closely. remember it was assumed you have a json file or json/php file, and in
//most cases you get your json data format from PHP file. so we assume its from a php file.
//also note that php calls to db can have a LIMIT. so in this case my PHP file data LIMIT 
//was set to 5. because of infinite scrolling, i need to know the id of the last element 
//from my returned data. so i write the following. note that my row.id_comments which is my
 //value i want to get was written into an input whose visibility is hidden. this is to 
//enable me over write its value when the last id changes.
            if (i==4)
            {
            //set last id value
            $('#last_id').val(row.id_comments);
            } 

    });
    }
    }

next is to implement pulltorefresh.js much woun't be said about this because the example in iscroll4 is clear.

var myScroll,
    pullDownEl, pullDownOffset,
    pullUpEl, pullUpOffset,
    generatedCount = 0;

function pullDownAction () {
        var el;
        el = document.getElementById('responsecontainer');

var url = "http://localhost/public_html/landing.php?token=78654567897654356789976546789&valid=jhjhjjhjhkhj";

        $.ajax({
        type: 'GET',
        url: url,
        contentType: "application/json; charset=utf-8",
        dataType: "jsonp",
        // Evaluate text as a json expression
        converters: {"text jsonp": jQuery.parseJSON},
        timeout:30000,
        async: true,
        jsonp: true,
        jsonpCallback: "myJsonMethod",
        error: function(){
        myScroll.refresh(); //do nofin
        },
        success: function(data){
        //console.dir('success');
        ajax.parseJSONP(data);
        }
        });
$.ajaxSetup({ cache: false }); //fetch data from db not cache content


var ajax = {  

    parseJSONP:function(data){
        $.each(data, function(i, row) {

        if (i==0){
        $("#responsecontainer").html('');
        }

        var ul = '<li>'+row.myjsondatakey+'</li>';
        $(ul).appendTo(el);


if (i==4)
            {
            //set last id value
            $('#last_id').val(row.id_comments);
            } 
        myScroll.refresh(); // Remember to refresh when contents are loaded (ie: on ajax completion)

});
}
}
}



    function loaded() {
        pullDownEl = document.getElementById('pullDown');
        pullDownOffset = pullDownEl.offsetHeight;

        myScroll = new iScroll('wrapper', {
           scrollbarClass: 'myScrollbar',
            useTransition: true,
            topOffset: pullDownOffset,
            onRefresh: function () {
                if (pullDownEl.className.match('loading')) {
                    pullDownEl.className = '';
                    pullDownEl.querySelector('.pullDownLabel').innerHTML = 'Pull down to refresh...';
                } 
            },
            onScrollMove: function () {
                if (this.y > 5 && !pullDownEl.className.match('flip')) {
                    pullDownEl.className = 'flip';
                    pullDownEl.querySelector('.pullDownLabel').innerHTML = 'Release to refresh...';
                    this.minScrollY = 0;
                } else if (this.y < 5 && pullDownEl.className.match('flip')) {
                    pullDownEl.className = '';
                    pullDownEl.querySelector('.pullDownLabel').innerHTML = 'Pull down to refresh...';
                    this.minScrollY = -pullDownOffset;
                } 
            },

//here is where infinite scroll comes in
                onScrollEnd: function () {
                //infinite scroll started
                if(Math.abs(this.maxScrollY) - Math.abs(this.y) < 10)
                {
                // Do infinite if scroll is 10px from the bottom.
                doInfinite_scroll();
                }

                //infinite scroll ended

                if (pullDownEl.className.match('flip')) {
                    pullDownEl.className = 'loading';
                    pullDownEl.querySelector('.pullDownLabel').innerHTML = 'Loading...';                
                    pullDownAction();   // Execute custom function (ajax call?)
                } 
            }
        });

        setTimeout(function () { document.getElementById('wrapper').style.left = '0'; }, 800);
    }


    document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false);

    document.addEventListener('DOMContentLoaded', function () { setTimeout(loaded, 200); }, false);

and last but not the least the main infinitescroll.js recall that we had previously placed a call to this function in pulltorefresh.js where we said if scroll bar is 10px to the end inifite scroll should be triggered. Then we have this as the shot to be fired.

function doInfinite_scroll()
{
        var last_id = $('#last_id').val();
        var searching = false;
        if (!searching) { // only initiate a new ajax request if this variable is false this is to avoid data duplication.
        var el;
        el = document.getElementById('responsecontainer');
        var url = "http://localhost/public_html/landing_more.php?last_id="+last_id+"&token=9876543456789765432456789876543&valid=jhjhjjhjhkhj";
        // -------------------------------------------

        $.ajax({
        type: 'GET',
        url: url,
        contentType: "application/json; charset=utf-8",
        dataType: "jsonp",
        // Evaluate text as a json expression
        converters: {"text jsonp": jQuery.parseJSON},
        timeout:30000,
        async: true,
        jsonp: true,
        jsonpCallback: "myJsonMethod",
        error: function(){
        myScroll.refresh(); //do nofin
        },
        beforeSend: function()
        {
        //add loading image i dint bcos the image or values becomes double in a case of network delay
        searching = true; // set variable to true
        },
        success: function(data){
        searching = false; // set variable to false
       //console.dir('success');
        ajax.parseJSONP(data);

        }
        });
        $.ajaxSetup({ cache: false });//fetch data from db not cache content
        var ajax = {  

        parseJSONP:function(data){
        $.each(data, function(i, row) {


        var ul = '<ul>'+row.comments+'</ul>';
        if (i==1) //bcos its php data limit was set to 2 so its always N-1 i.e yourlimit - 1
        {
        //resset lastdeed id value
        $('#lastdeed_id').val(row.id_comments); //update the value in the hidden input field to enable the next set of data load properly
        } 
        $(ul).appendTo(el);
        myScroll.refresh();     // Remember to refresh when contents are loaded (ie: on ajax completion)

});
}
}
}
}

so just in case you are lost with what the php file should look like here you go. This file is landing.php

this next file is for infinite scrolling and it is called landing_more.php

<?php
// Prevent caching.
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 01 Jan 1996 00:00:00 GMT');

if ((isset($_GET['token'])) && (isset($_GET['validator']))) {

@require_once('connect/connectionfile.php');  


$token=htmlspecialchars($_GET['token'],ENT_QUOTES);
$token= mysql_real_escape_string($token);
$validator=htmlspecialchars($_GET['validator'],ENT_QUOTES);
$validator= mysql_real_escape_string($validator);
$last_id=htmlspecialchars($_GET['last_id'],ENT_QUOTES);
$last_id=mysql_real_escape_string($last_id);


//now validating the token
$sql="SELECT * FROM bla WHERE blabla='$token'";
$result=mysql_query($sql);

//if token exists
if(mysql_num_rows($result))
{
 header('Content-type: application/json');
//valid token
 $fakevalue = mysql_fetch_assoc($result);
 $uid = $fakevalue['id'];
 $results = array();
 $query = "SELECT * FROM bla bla WHERE bla && bla bla && a.id_comments < '$last_id' ORDER BY a.id_comments DESC LIMIT 0, 2";
 $rsult = mysql_query($query);
 while($value = mysql_fetch_assoc($rsult, MYSQL_ASSOC))
 $results[] = $value;
 {
 echo "myJsonMethod".'('.json_encode($results).')'; //ECHO RESULTS IN JSONP FORMAT

}

}
else 
{
 //Invalid token
 header('Content-type: application/json');
 echo "myJsonMethod({\"token\":".utf8_encode(json_encode('failed'))."})";
}
}
else {
    header('Content-type: application/json');
    echo "myJsonMethod({\"token\":".utf8_encode(json_encode('Invalid token check parameters'))."})";
    }
?>

javascript - iScroll lite find when I have reached the end of the scro...

javascript jquery html5 iscroll