Salta al contingut principal

“Infinite” Scroll to Load More Content Pagination with jQuery

Pagination with numbers is, in many ways, counter intuitive and time consuming for the user. They have to stop, click on a number, wait for the page to load, and then continue their search. Some websites such as facebook have opted out of this notion of pagination for a system which loads content automatically as the user scrolls. In this tutorial that is what we’re going to be making.


How it works


I’ve created a little plugin that allows us to accomplish our goal. Simply put the plugin checks if the user is at the bottom of the container you specify and loads more content accordingly. Then this data is sent to an ajax file which processes what posts to show.



// Check the user is at the bottom of the element
if($(window).scrollTop() + $(window).height() > $this.height() && !busy) {

// Now we are working, so busy is true
busy = true;

// Tell the user we're loading posts
$this.find('.loading-bar').html('Loading Posts');

// Run the function to fetch the data inside a delay
// This is useful if you have content in a footer you
// want the user to see.
setTimeout(function() {
// This is the Ajax function
getData();

}, $settings.delay);

}


The key line here is if($(window).scrollTop() + $(window).height() > $this.height() ... This is basically saying, if the user scroll position is greater than the height of the element targeted, then more elements should be loaded.


What is Ajax?


AJAX Example

Ajax is how we send data to files when an event happens in javascript. For example, when we scroll we want to send some data to another file to figure out what to do. That file is usually a PHP file which will process the data sent, and then you can do something like grab information from a database. So how do we do this with jQuery? Since we’re posting data, we use the $.post function. It looks a little like this:



$.post('file.php', {

information : 'to be sent',
to : 'file'

}, function(data) {

}

});


So in the above example we end the information (thats the bit inside the first set of curly brackets) to the file, file.php. When the information is sent it will return some information in the form of a data variable, and we can then use that data to return information to the user via Javascript.


The ajax file


The ajax file is going to have to be customized to fit your needs. All you have to do is grab some information from the MySQL database of your choice with some PHP. I have created a very basic ajax.php file that grabs information from a wordpress MySQL database and displays the content with the title and link. It looks a little like this, but it will be included with the download files in the download link above.



<?php

mysql_connect('localhost', 'username', 'password') or die();
mysql_select_db('database');

$offset = $_POST['offset'];
$postnumbers = $_POST['number'];
$query = str_replace('\\', '', $_POST['query_string']);


$run = mysql_query($query." LIMIT ".$postnumbers." OFFSET ".$offset);


while($row = mysql_fetch_array($run)) {

$content = substr(strip_tags($row['post_content']), 0, 500);

echo '<h1><a href="'.$row['guid'].'">'.$row['post_title'].'</a></h1><hr />';
echo '<p>'.$content.'...</p><hr />';

}

?>

Using the Plugin


Once you have your ajax file sorted out, its just a case of running the plugin. There are a bunch of variables you can determine, but it’s important that you define the query if you’re using the original ajax.php file listed above.


To run the plugin just upload all the files and create a container in your HTML called #content or whatever you want to call your container. Then run the plugin on that. Easy!





$(document).ready(function() {

$('#content').scrollPagination({

nop : 10, // The number of posts per scroll to be loaded
offset : 0, // Initial offset, begins at 0 in this case
query : "SELECT * FROM wp_posts WHERE post_status = 'publish' AND post_type ='post' ORDER BY id DESC", // The query you are running against the MySQL database
error : 'No More Posts!', // When the user reaches the end this is the message that is
// displayed. You can change this if you want.
delay : 500, // When you scroll down the posts will load after a delayed amount of time.
// This is mainly for usability concerns. You can alter this as you see fit
scroll : true // The main bit, if set to false posts will not load as the user scrolls.
// but will still load if the user clicks.

});

});


In the download you’ll find the files necessary to do everything I’ve shown you. Since I can’t include database details you will have to supply your own which you can edit in the ajax.php file. And that’s it! Have a good day!








via InsertHTML http://www.inserthtml.com/2013/01/scroll-pagination/?utm_source=feedburner&utm_medium=feed&utm_campaign=Feed%3A+inserthtml+%28InsertHTML%29

Comentaris

Entrades populars d'aquest blog

15 Tutoriales CSS3 para mejorar tus paginas web

15 Tutoriales CSS3 para mejorar tus paginas web : Les dejo una pequeña recopilación de tutoriales CSS3 que espero sean de utilidad para ustedes, intentamos hacer una recopilación bastante completa para crear impresionantes diseños web con CSS3 y aprovechar las bondades de CSS3 incluso para aplicar efectos, son un total de 15 tutoriales CSS3 gratis . Crear menu dropdown con CSS3 Crear breadcrumbs con estilo Transiciones de paginas con CSS3 Crear timeline con CSS3 y jQuery Reproductor de video con HTML5, CSS3 y jQuery Crear efecto acordion CSS3 Aplicar degradado a texto Crear texto en curva con CSS3 y jQuery Aplicar textura a texto con Magic Pill Crear slider de imagenes con CSS3 y jQuery Rotar texto con CSS3 Crear menu vertical con CSS3 Crear formulario con HTML5 y CSS3 Crear efecto de imagenes apiladas con CSS3 Aplicar estilos para imagenes con CSS3  

Learn Composition from the Photography of Henri Cartier-Bresson

“Do you see it?” This question is a photographic mantra. Myron Barnstone , my mentor, repeats this question every day with the hopes that we do “see it.” This obvious question reminds me that even though I have seen Cartier-Bresson’s prints and read his books, there are major parts of his work which remain hidden from public view. Beneath the surface of perfectly timed snap shots is a design sensibility that is rarely challenged by contemporary photographers. Henri Cartier-Bresson. © Martine Franck Words To Know 1:1.5 Ratio: The 35mm negative measures 36mm x 24mm. Mathematically it can be reduced to a 3:2 ratio. Reduced even further it will be referred to as the 1:1.5 Ratio or the 1.5 Rectangle. Eyes: The frame of an image is created by two vertical lines and two horizontal lines. The intersection of these lines is called an eye. The four corners of a negative can be called the “eyes.” This is extremely important because the diagonals connecting these lines will form the breakdown ...

El meu editor de codi preferit el 2024, que això ja se sap que va canviant 😄

Visual Code Visual Code és un editor de codi font lleuger, però potent que s’executa al teu escriptori i està disponible per a Windows, macOS i Linux. Compta amb suport integrat per a JavaScript, TypeScript i Node.js i té un ric ecosistema d’extensions per a altres llenguatges i entorns d’execució (com C++, C#, Java, Python, PHP, Go, .NET).  És una eina ideal per a desenvolupar i depurar aplicacions web i en el núvol. Per què Visual Code? Visual Code té molts avantatges com a editor de codi font, com per exemple: És gratuït, ràpid i fàcil d’instal·lar i actualitzar. Té un ampli ecosistema d’extensions que et permeten afegir funcionalitats i personalitzar la teva experiència de desenvolupament. Té un suport integrat per a molts llenguatges i entorns d’execució, i et permet depurar i executar el teu codi des del mateix editor. Té una interfície senzilla i elegant, amb diferents temes i modes de visualització. Té un sistema de sincronització de configuracions que et permet guardar les...