jQuery: infinite scroll and the back button - javascript

OK so I know this causes problems with everyone, and it's causing problems with me too. I'm using the infinite scroll plugin on a client's site, in combination with the isotope plugin to load in their products sequentially, the problem is though as they have 1000's of products, anyone browsing the site then clicking into a product, when they click the back button they'll be returned back to the top (or just above the fold of page one), which is causing quite a lot of issues.
My markup is as follows below:
$(window).load(function () {
var $container = $('.products-grid-wrap');
$container.imagesLoaded(function () {
$container.isotope({
itemSelector: '.products-grid-block',
filter: '*:not(.hidden), .products-grid-block',
animationEngine: 'best-available',
layoutMode: "perfectMasonry",
perfectMasonry: {
columnWidth: 280,
rowHeight: 310
}
});
$container.infinitescroll({
navSelector: '#page_nav', // selector for the paged navigation
nextSelector: '#page_nav a', // selector for the NEXT link (to page 2)
itemSelector: '.regular-product-block, .products-grid-block', // selector for all items you'll retrieve
pixelsFromNavToBottom: Math.round($(window).height() * 1.5),
bufferPx: Math.round($(window).height() * 1.5),
loading: {
finishedMsg: 'No more products to load.',
img: 'http://www.by-form.net/wp-content/uploads/2014/11/ajax-loader-big.gif'
}
},
// call Isotope as a callback
function (newElements) {
var $newElems = $(newElements);
$newElems.imagesLoaded(function () {
$container.isotope('insert', $newElems);
$('.products-grid-rollover-block').hide();
if(newElements.length > 0){
setTimeout(function () {
$container.infinitescroll('retrieve');
$('.products-grid-wrap').isotope('reLayout');
//$('.products-grid-wrap').isotope({
//sortBy: 'category',
//sortAscending: false });
}, 1000);
}
});
});
setTimeout(function () {
$container.infinitescroll('retrieve');
}, 3000);
});
});
Any solutions or suggestions would be massively appreciated!

You can try scroll-frame.It is a bit old may be the answer for you. Here is a link to an infinite scroll demo using it.
scrollFrame will hijack the user's click for elements that match the query selector you pass in and instead of reloading the page it will append a modal-like iframe that sits on top of your viewport and points to the element's href. It then uses HTML5 history APIs to make the back-button function as expected.

This can be a bit new solution of such problems.
https://github.com/highrisehq/snapback_cache
This is what is say's ...
Many apps today have some concept of an infinite scrolling feed: Facebook, Twitter, LinkedIn and many more. Almost all of them suffer from the same problem. If you click on something in the feed that brings you to a new page, when you hit the back button or try to return to that original feed, your place is lost. All the scrolling is gone.
At Highrise we had that same problem. So this is the library we use to fix that. We call it our Snapback Cache, and it's made a big improvement to how people can use infinite scroll in our app and still get a lot of work done without losing their place.

We solved this problem with a combination of (1) opening the page linked to on the infinite scroll page in a new tab; (2) using javascript to return to the parent.
Since I have seen a lot of comment about the difficulty of returning to the parent, I am posting our code for that below. The two functions are put into onclick attributes in the anchor tags used for the navigation buttons.
Using the name of the parent window solves the problem of intervening tabs opened before returning to the parent; without this, the tab returned to could be the most recently opened tab, rather than the parent.
/**
* open url in separate tab
* saves name of parent window for easy return
* #param url
*/
function gotoTab(url)
{
window.name = 'parent';
window.open(url);
}
/**
* uses name of parent
*/
function returnToParent()
{
var goBack = window.open('', window.opener.name);
window.top.close();
goBack.focus();
}

Related

How to add msnry.reloadItems() to vanilla JS script

I am very new in js, javascript, ajax, etc., I am using php and build only wordpress sites. Today I trying make to my site the hybrid pagination, what someone call it the "HolyScroll or Holy Scroll", the target this:
http://scrollsample.appspot.com/items
So I working on the infinite-scroll.com with Desandro's Masonry and my code now it looks like this (I did this in the last 5 hours...):
var grid = document.querySelector('.container');
var msnry;
imagesLoaded( grid, function() {
// init Isotope after all images have loaded
msnry = new Masonry( grid, {
itemSelector: '.item'
});
});
// -----------
var elem = document.querySelector('.container');
var infScroll = new InfiniteScroll( elem, {
// options
path: 'page/{{#}}/',
append: '.item',
history: 'push',
historyTitle: true,
prefill: true,
// load pages on init until user can scroll
scrollThreshold: 1000,
// trigger scrollThreshold event when viewport is <100px from bottom of scroll area
status: '.page-load-status',
});
// element argument can be a selector string
// for an individual element
var infScroll = new InfiniteScroll( '.container', {
// options
});
So finally works the infinite scroll, the history, the masonry (only on the first call) and the imagesLoaded, And now need paste to this the reloadItems option, but dont working...
Here is the guide: https://masonry.desandro.com/methods.html#reloaditems
Please, someone could help me? I can not find a simple tutorial to this with Vanilla JS, in turn the JQuery versions not working for me...
*Unfortunately MarkovskI drew my attention not everyone can click on a link, so I copy here, what Desandro write on his site:
"For frameworks like Angular and React, reloadItems may be useful to apply changes to the DOM to Masonry."
// vanilla JS
msnry.reloadItems()
So here is the "Holy Scroll", the hybrid, ajax / js loaded infinite scroll WITH pagination, what search engines loves, so this totally user and SEO friendly:
Source sites:
https://infinite-scroll.com/
https://masonry.desandro.com/
https://imagesloaded.desandro.com/
So, I just now learning php, I am only webdesigner and after I realized, the ALL wordpress plugins what promises you "infinite scroll" (like Ajax Load More, Ajax Pagination & infinite Scroll, DMD Infinite Scroll, Jetpack, YITH Infinite Scroll and etc.) rip-off and KILL YOUR ALL SEO if you using these plugins without LICENSE, I started looking the solution on the net. The first what it comes face to face the Google' Webmaster Central Blog:
https://webmasters.googleblog.com/2014/02/infinite-scroll-search-friendly.html
So after this article I knew what I wanted, but by the time, what I found it the keywords (thus: the browser history about infinite scroll) and the simple fact, that now need building my masonry layout (because up to now I using the Ajax Load More plugin, and this did it the masonry to me), so I never learning JS... I worked on this in the last ~35 hours, but you can instantly learn to do it yourself, as you read it all along. (The long introductory serving the keywords, to find you here too.)
So, you can modify your infinite scroll options off this official guide:
https://infinite-scroll.com/options.html
The VERY IMPORTANT THING, WHAT NEED FOR YOU, IS THIS:
https://infinite-scroll.com/options.html#history
So, put these links (or follow these steps: https://infinite-scroll.com/#install) to your footer (Or header, but Google recommend that call .js and .css files in footer, thus reduce it you pageload.):
<script src="https://unpkg.com/infinite-scroll#3/dist/infinite-scroll.pkgd.min.js"></script>
<script src="https://unpkg.com/masonry-layout#4/dist/masonry.pkgd.min.js"></script>
<script src="https://unpkg.com/imagesloaded#4/imagesloaded.pkgd.min.js"></script>
And here is so the full "Holy Scroll" code with masonry layout what using images Loaded (imagesLoaded), so never more overlapping your images.
Just Put This code to your footer between: <script></script>
var grid = document.querySelector('.container');
var msnry = new Masonry( grid, {
itemSelector: '.youritem', // select none at first
});
// initial items reveal
imagesLoaded( grid, function() {
msnry.options.itemSelector = '.youritem';
var items = grid.querySelectorAll('.youritem');
msnry.reloadItems( items ); // This reload the masonry layout after the first call
msnry.layout(); // This restrain the overlapping on the first call
});
//-------------------------------------//
// init Infinte Scroll
var infScroll = new InfiniteScroll( grid, {
// options
path: 'page/{{#}}/', // YOUR PAGINATION STRUCTURE !!!IMPORTANT!!! REPLACE IT
append: '.youritem',
history: 'push',
historyTitle: true,
prefill: true,
// load pages on init until user can scroll
scrollThreshold: 1000,
// trigger scrollThreshold event when viewport is <100px from bottom of scroll area
// (I using 1000, that my users never have to wait for the loading of the next page...
// The calling it will start to working, before the screen shows the bottom of the page...)
status: '.page-load-status',
outlayer: msnry,
});
Okay, so replace it the .container to YOUR site container what includes the items (items = posts, images, anything) and replace it the .youritem to your grid item (so the div what include ONE item)!
Very important, that you replace the value of the path: to your pagination structure, where the current page's number is {{#}}! (So if your site works thus: yourdomain.com/page/2/ your path value is: 'page/{{#}}/')
Finally you make your design with .css (Included the masonry parameters (width, etc.)!)

jQuery history usage

I have created a webpage that uses jQuery to show and hide elements. The obvious problem now arose; the back and forward browser buttons don't work anymore as everything is loaded within a single location.
I know the answer lies within jQuery History but after busting my head for several hours on their website and examples given here on stackoverflow, I still cant manage to:
A) create a history entry (I think i got this covered but not 100% sure)
B) animate the page transition with my own function (displayed beneath)
This is the website: www.grommit.nl
There are 4 sub-pages that require a history entry when called upon.
This code shows the transition of the "wordpress page". The other pages work in a similiar way. (so far I have only managed to generalize the last part of the pageload with the "LoadPageContent" function, the bit before that is different with every page)
var LoadPageContent = function() {
$(".sceneBody").slideDown(function() {
$(".aftertitle").css('width', '4em');
$(".mediacontainer").fadeTo('0.3s', 1,)
});
$("#goWordpress").click(function () {
$("#homeScene").fadeOut(function () {
$("#wordpressMessage").fadeIn(function() {
$(this).delay(300).slideUp(function() {
$("#wordpressPage, #grommitFixed").slideDown(function() {
LoadPageContent();
});
});
});
});
});
this is the function that is currently working as a previous button within the DOM. I would like this function to execute when the previous button is clicked.
var goBack = function() {
$(".aftertitle").css('width', '0em')
$(".mediacontainer").fadeTo('0.3s', 0, function() {
$(".scenebody, #grommitFixed").slideUp(function() {
$("*[id*=Page]:visible").each(function() {
$(this).slideUp(function() {
$("#homeScene").fadeIn();
});
});
});
});
};
In html5 you have something called pushstate, that you can use to tell the browser what to go back to. Check out:
html pushstate

jquery infinite scroll plugin - loading and memory issues

I am using infinate scroll plugin (by Paul Irish). I want to use custom functions when the next page is loading and when the maxPage is reached.
I have tried the below based on the documentation, however this starts the loading function but doesn't ever call the finished function. Its not calling the next page either when I look in the console. What am I missing?
// Infinite Ajax Scroll configuration
$container.infinitescroll({
navSelector: "div.paginate",
nextSelector: "div.paginate a",
itemSelector: "div.element",
maxPage: 5,
loading: {
start: function(){
alert('started');
},
finished: function(){
alert('finsihed loading');
}
}
},
function(newElements) {
var $newElements = $(newElements).css({opacity: 0});
//remove the first item
$newElements.splice(0, 1);
$container.isotope('appended', $newElements);
}
});
});
The scrolling could go on for pages and pages until the browser crashes due to memory issues, I therefore need to stop infinite scrolling when the current page gets to maxPage and allow the user to select a "Load More" button. Hopefully solving memory issues.
This is discussed in the link below but I cannot find any further documentation on how to do this exactly and cann't even get the above sample to work.
https://github.com/paulirish/infinite-scroll/issues/300
First, ensure it works will the minimum options (plus console debug messages):
$container.infinitescroll({
navSelector: "div.paginate",
nextSelector: "div.paginate a",
itemSelector: "div.element",
debug: true
});
If it does, add in options until it breaks.
I recommend debugging the start/finished functions in the console, like this:
loading: {
start: function(){
console.log('started');
},
finished: function(){
console.log('finsihed loading');
}
}
Consider adding the errorCallback option to debug ajax issues.

jQuery Isotope and InfiniteScroll - Appended items not being properly placed in the layout

I've got Isotope on the page and it works independently. I've got InifiniteScroll on the page and it works independently. When InfiniteScroll loads new items, I append them to my container but instead of being placed properly in the layout, they all appear in a single column down the left-hand side of the container. Here's my JS:
$(function() {
var container = $('#wall .page');
container.isotope({
itemSelector: '.brick'
});
container.infinitescroll({
navSelector: "nav.pagination",
nextSelector: "nav.pagination a[rel=next]",
itemSelector: ".brick",
loading: {
finishedMsg: 'No more items to load.',
img: 'http://i.imgur.com/qkKy8.gif'
}
}, function (newElements) {
container.isotope('appended', $(newElements));
});
});
I have a hard time believing it's a CSS or html problem since Isotope handles the initial items on the first page without a problem. I'm willing to provide more information if you can let me know what you need to see.
For anyone else experiencing this same issue, I ended up finding the answer on my own. In my case, the problem was in the selector for my container.
var container = $('#wall .page');
The problem is that more than one item with the class .page existed inside of the #wall element. Because of this, Isotope was apparently getting confused about exactly where to put things. Always make doubly sure that your jQuery selectors are correct. For me, this fixed it:
var container = $('#wall > .page');

Jscroll pagination plugin

i have download this good plugin
http://andersonferminiano.com/jqueryscrollpagination/
and i use this code for do a call to my db and show all the result. The my problem is that i can't stop the showing results when are finish in the database, i wouold like stop the pagination and no repeat the same result. how can i do it? thank you so much
$(function(){
$('#content').scrollPagination({
'contentPage': 'democontent.html', // the page where you are searching for results
'contentData': {}, // you can pass the children().size() to know where is the pagination
'scrollTarget': $(window), // who gonna scroll? in this example, the full window
'heightOffset': 10, // how many pixels before reaching end of the page would loading start? positives numbers only please
'beforeLoad': function(){ // before load, some function, maybe display a preloader div
$('.loading').fadeIn();
},
'afterLoad': function(elementsLoaded){ // after loading, some function to animate results and hide a preloader div
$('.loading').fadeOut();
var i = 0;
$(elementsLoaded).fadeInWithDelay();
if ($('#content').children().size() > 100){ // if more than 100 results loaded stop pagination (only for test)
$('#content').stopScrollPagination();
}
}
});
// code for fade in element by element with delay
$.fn.fadeInWithDelay = function(){
var delay = 0;
return this.each(function(){
$(this).delay(delay).animate({opacity:1}, 200);
delay += 100;
});
};
});
That plugin actually isn't very good. I'm looking at the plugin's code, and sure enough, it doesn't provide a way to detect when you're at the end of the content.
If you go to the plugin page and scroll down, it appears to be working quite nicely. However, when you look at the file democontent.html (he's hidden the text, you have to view the source) where the data is being retrieved from, you'll see it's only 17 items. But, it keeps loading bogus data as you scroll down.
Not only does the plugin not detect the end of the data, but it also doesn't provide a way of stopping at all. If you'll notice, Anderson told the plugin to stop after 100 items are loaded, but he did this only in his example instead of writing this feature into the plugin.
So, that's why your content isn't stopping. You could try modifying his plugin yourself, but if you'd rather just change plugins, I'd recommend Infinite Scroll, by Paul Irish.
You can use mkscroll plugin with is provide you more functionality link for mk scroll is below.
https://github.com/maulikkanani/Scroll-Pagination
jQuery(window).mkscroll({
limit:10,
total:100,
});
there are many other option in that.
If any one phasing the problem here is the solution: the jscroll will stop the loading the content once the 'next page' link is not available.. so please check when you want to stop loading the content then 'next page' link is not getting loaded in the last content which is appended.

Categories