jQuery infinite-scroll Not Triggering - javascript

I'm making a simple little website to apply a different formatting style to Reddit posts, I'm trying to add the infinite-scroll jQuery plugin but it doesn't do anything. I tried following the (very simple) instructions on the infinite-scroll page and when it didn't do anything I thought I must have entered something wrongly, but then I just copy/pasted the code from the Masonry/Infinite-Scroll example and it still didn't work. Masonry is working perfectly (finally) but I just can't figure out what is wrong with infinite-scroll. I understand the basics of jQuery and JavaScript, but obviously not as much as most of you people, so could you please help me out and let me know what is wrong? My site is live at reddit.ymindustries.com.
Thanks heaps, you guys have rarely failed me so far.
YM
EDIT: If there aren't enough images to fill up the page on the homepage, visit reddit.ymindustries.com/r/aww for more images.
EDIT 2: I believe I located the issue, it is described here: https://github.com/paulirish/infinite-scroll/issues/5
Now to figure out a fix...
EDIT 3: Added a little bit of a hack in to make it sort of work, but it just seems to loop the second page endlessly now. Hmm...

I think your problem is actually css. Make your page longer that client area height. add more images to $container
Point is, botom edge of your $container need to pass bottom of window so scroll event fires so infinite scroll can react on this event and calculate weather or not edge is reached
BTW, in same cases, for instance, when I shrink my window, the example you set is working.
=== UPDATE ===
I found some time to play with infinitescroll and here is final working script, just set pathParse method in your script
$(function () {
var $container = $('#itemContainer');
$container.imagesLoaded(function () {
$container.masonry({
itemSelector:'.item'
});
});
$container.infinitescroll({
navSelector:'.navigation', // selector for the paged navigation
nextSelector:'.navigation #next', // selector for the NEXT link (to page 2)
itemSelector:'.item', // selector for all items you'll retrieve
bufferPx:40,
debug:true,
columnWidth:function (containerWidth) {
return containerWidth / 5;
},
loading:{
finishedMsg:'No more pages to load.',
img:'http://i.imgur.com/6RMhx.gif'
},
pathParse: function(path,page){
return $(this.nextSelector).attr("href");
}
},
// trigger Masonry as a callback
function (newElements) {
// hide new items while they are loading
var $newElems = $(newElements).css({ opacity:0 });
// ensure that images load before adding to masonry layout
$newElems.imagesLoaded(function () {
// show elems now they're ready
$newElems.animate({ opacity:1 });
$container.masonry('appended', $newElems, true);
});
//console.log("test (never fired :( )");
}
);
});
Now, since your next link will not update by it self (http://reddit.ymindustries.com/?after=t3_yh4av), you need to change the callback to pull out last element from ajax response and change next link... could be something like this
function (newElements) {
// hide new items while they are loading
var $newElems = $(newElements).css({ opacity:0 });
// ensure that images load before adding to masonry layout
// ======> if query parameter after=... is caring filename then do this
var lastImageUrl= $newElements[$newElements.length-1].attr("src");
var lastFileName= lastImageUrl.substring(lastImageUrl.lastIndexOf("/") +1, lastImageUrl.lastIndexOf("."));
$("#next").attr("href", "http://reddit.ymindustries.com/?after="+lastFileName);
$newElems.imagesLoaded(function () {
// show elems now they're ready
$newElems.animate({ opacity:1 });
$container.masonry('appended', $newElems, true);
});
//console.log("test (never fired :( )");
}

You also need to take care of wich version of infinite-scroll your using since if you use the ones that comes with masonry/isotope (version 2.0b2.110713), both need a little hack in order to call the function and not use the predefined array:
//old code, to be changed (line 489)
desturl = path.join(opts.state.currPage);
// new code
desturl = (typeof path === 'function') ? path(opts.state.currPage) : path.join(opts.state.currPage);
This is already fixed in the newer versions of infinite-scroll

I had the same problem with jQuery's "infinitescroll" and Masonry. You might just solve this by giving your page more initial items so that the plugin's scrolling detection kicks in.
In WordPress this is under the "Reading" settings. By default WordPress only opens 10 items at a time. You could increase that number to 100/page to be more sure the window will be full initially. I had some code here that was just horrible, turns out I just needed longer pages, not more code.
So it's difficult to test these plugins on large displays if you don't have enough images. Maybe the solution is to scale the images larger on large displays so you're more sure about getting your content below the fold.
If you think someone might get to your website with a really huge display, I'm not sure what the answer is other than showing more items/page and maybe adding $('#masonry').infinitescroll('retrieve'); to your footer to load an extra page just in case.

Related

Load a jquery event only after the preloader ends

My website is : https://365arts.me/
So it loads about 16mbs of pics(Yes I know, I'm stupid. I'll try to change it very soon, also if someone could tell me a way to reduce size of do something else(like dynamic loading only when needed, if something like that exists) I'd be very grateful).
I added a preloader for it using:
[html]:
<div class="spinner-wrapper">
<div class="spinner">
<div class="dot1"></div>
<div class="dot2"></div>
</div>
</div>
and corresponging [jquery]:
<script>
$(document).ready(function() {
//Preloader
$(window).on("load", function() {
preloaderFadeOutTime = 500;
function hidePreloader() {
var preloader = $('.spinner-wrapper');
preloader.fadeOut(preloaderFadeOutTime);
}
hidePreloader();
});
});</script>
this works well but the problem is I have a javascript code that comes and says Hi! but it runs only for 2.8 seconds. So if loading takes up more than that, It doesnt show up. Can someone please tell me how to make sure that it loads only exactly after loading is completed.
Thanks a ton.
Code for my website:
https://github.com/richidubey/365-Days-Of-Art/blob/master/index.html
this may work
document.addEventListener('DOMContentLoaded', function() {
// your code here
}, false);
if you are happy with pure javascript
My first suggestion is to just get rid of the "Hi!" message since you already have a splash page in the form of the loader. But if you really want that second splash page, you can use the JQuery when() method:
$(window).on("load", function() {
$.when($('.spinner-wrapper').fadeOut(500)).then(displaySplashPage);
});
This assumes that displaySplashPage() is your function for showing the "Hi!" message.
You don't need $(document).ready() and window.on("load") here. Document ready waits for the HTML to be built, then applies event listeners/functions/etc to the structure. Window onload waits for everything to get loaded, then fires. In your case, you're trying to wait for all your pictures to load, so you only need onload.
You might need to have a container around all your main content set to opacity: 0 that switches to opacity: 1 as part of displaySplashPage(). That would prevent things from leaking through as you do the .fadeOut() on the loader.
JavaScript version - run js code when everything is loaded + rendered
window.onload = function() {
alert("page is loaded and rendered");
};
jQuery version (if you need it instead pure JS)
$(window).on('load', function() {
alert("page is loaded and rendered");
});
You can try this:
<script>
// Preloader
$(window).on("load", function() {
fadeOutTime = 500;
sayHelloDuration = 5000;
function hideSayHello() {
var sayHello = $('.say-hello');
sayHello.fadeOut(fadeOutTime);
}
function hidePreloader() {
var preloader = $('.spinner-wrapper');
preloader.fadeOut(fadeOutTime);
setTimeout(function() {
hideSayHello();
}, sayHelloDuration);
}
hidePreloader();
});
</script>
Also, remove the code from lines 83 ~ 87:
<script>
$(document).ready(function() {
$('.say-hello').delay(2800).fadeOut('slow');
});
</script>
About your website performance, you can improve a lot of things right now:
Use smaller thumbnail images on your front page, don't load FULL SIZE images at once. "work-showcase" section is really heavy without real necessity.
Try to incorporate src-set and smaller images for small screens, larger/heavier images for bigger screens. All modern browsers support it, and it will improve performance/loading speed.
Try to lazyload your big images, e.g. only when users scroll down to them, not before. It may take some work to integrate it with your image viewer, but it will additionally speed things up on initial load. My favorite library for this is this one: https://github.com/aFarkas/lazysizes but, you may find something else...
Unrelated to your original question, I have noticed that you have a bug in your HTML - see this screenshot. What kind of code editor do you use? Instead of empty space it apparently inserts invisible dots symbols which are not good. Actually, it's not the invisible dot (that's my editor's space indentation symbol), it's caused by 2 long dash (instead of short dash or minus) in your code after opening html comment tag:

shorthand for .load() ajax links with loader

here's the structure of the code: http://jsfiddle.net/ss1ef7sq/
although it's not really working at js fiddle but the code itself is working as i've tested it locally through firefox.
this is where i've based this on: http://html.net/tutorials/javascript/lesson21.php
jquery/ajax:
$('#ep-101').click(function(){$('.main-container').load('link.html #ep101').hide().fadeIn(800);});
$('#ep-102').click(function(){$('.main-container').load('link.html #ep102').hide().fadeIn(800);});
$('#ep-103').click(function(){$('.main-container').load('link.html #ep103').hide().fadeIn(800);});
$('#ep-104').click(function(){$('.main-container').load('link.html #ep104').hide().fadeIn(800);});
$('#ep-105').click(function(){$('.main-container').load('link.html #ep105').hide().fadeIn(800);});
so my question is, is there a way to make it like a shorter code where it can just get the value of those #10ns or assuming that there will be a different page with it's own nest of unique ids without typing them individually? there's still a lot i don't understand with ajax so i'd appreciate it if anyone can help & explain at least the gist of it as well.
i've looked around online but i'm really stuck. i also at least found out that it's possible to add transitions but the way it's coded there is that it will only have the transition for the incoming page & not the one that will be replaced. i also have a prob with page loaders effects but i'll save it for when i'm stuck there as well.
thanks in advance. =)
Use classes instead of id's. Set href attribute which you want to load on click and access it via $(this).attr('href').
<a class="load-me" href="link1.html">link 1</a>
<a class="load-me" href="link2.html">link 2</a>
...
Script:
$('.load-me').click(function(e){
e.preventDefault();
$('.main-container').hide().load($(this).attr('href'), function() {
// ...
$(this).fadeIn(800);
})
});
JSFiddle
If you need the load to wait container hiding animation, you could make it other way.
$('.load-me').click(function(e){
e.preventDefault();
// get the url from clicked anchor tag
var url = $(this).attr('href');
// fade out the container and wait for animation complete
$('.main-container').fadeOut(200, /* animation complete callback: */ function(){
// container is hidden, load content:
$(this).load(url, /* load complete callback: */ function() {
// content is loaded, show container up
$(this).slideDown(200);
});
});
});
JSFiddle

Call jQuery when something happens

So I am using jQuery Masonry and I want to call some jQuery every time it loads posts:
function manipulate(id) {
$(id).each(function(){
if($(this).height()>200){
$('#container2').append(this);
} else{
$('#container').append(this);
};
});
};
So I want to call this function every single time that the next item in the Masonry container loads. This way it manipulates the item in the correct manner. How do I do that?
Update: description of Masonry
Masonry is a Javascript plug in that is like CSS floats forced to fit perfectly + infinite scrolling. It completely hides everything that would not be on page 1 if there was no infinite scroll, and then loads them when necessary. This means that my function will not affect any of the hidden items and needs to be recalled whenever Masonry loads the next set of items so that they appear in the right places. This could mean that without knowing Masonry, it is not necessarily possible for you to solve my problem, but you still can. A the end, Masonry "appends" the items to the Masonry container, and then "shows" them. So I guess what I need to do is append them to the correct containers after they have been appended to the Masonry container, but before it gets shown.
Masonry code:
$(window).load(function(){
var $wall = $('#container');
$wall.imagesLoaded(function(){
$wall.masonry({
itemSelector: '#entry, #entry_photo',
isAnimated : false
});
});
$wall.infinitescroll({
navSelector : '#page-nav',
nextSelector : '#page-nav a',
itemSelector : '.entry, .entry_photo',
bufferPx : 2000,
debug : false,
errorCallback: function() {
$('#infscr-loading').fadeOut('normal');
}},
function(newElements) {
var $newElems = $(newElements);
$newElems.hide();
$newElems.imagesLoaded(function(){
$wall.masonry( 'appended', $newElems,{isAnimated: false}, function(){$newElems.fadeIn('slow');} );
});
}); $('.entry').show(500);
});
I have tried putting the function in the Masonry blocks and even as the $newElems function to see if it will work when more images load, but it does not, and in fact somewhat breaks it.
How can I get it to run all the new elements loaded by Masonry through my jQuery so that they get appended to the right container?
You only declared one Masonry instance for container, container2 has no Masonry instance, so it can't infinitely scroll anything.
Also, ($(this).height()>200) will always be false if the image has not loaded yet, it'll default to undefined -> 0 > 200, which is always false. Either you need to wait for the image to load before placing it, or somehow get the dimensions of the image when the content is being loaded. You could hide it by default and place it in container, then on imagesloaded, check the height, and move it to the appropriate container and show it.
Another idea is to bind an action to jQuery's .on() ( http://api.jquery.com/on/ ). on() binds on future elements as well, assuming they are properly attached to the DOM (for example through .append() ). So for example you can bind .click() events, on elements that have not been created yet.
Finally you can do a neat trick and make .append() trigger an event. Then attach a handler for that event to the big container where things are appended, so a function is automatically called. Here is a good example of that on append() do something, and a jsfiddle http://jsfiddle.net/rzRVu/
PS. on a sidenote, I see you function takes as input an ID, but then you call .each(). Id's in html code should be unique.
Update. I missed that you tried to do it properly through masonry, what breaks exactly? I see you are calling .imagesLoaded() on a jQuery variable, is that a plugin?
So using things said on the answers provided, I messed around and discovered how it was done...so the 'appended' part in imagesLoaded just needed to be replaced with the function! It was really a simple answer...I just had to replace this:
$wall.masonry( 'appended', $newElems,{isAnimated: false},
function(){$newElems.fadeIn('slow');} );
with this:
$wall.masonry(manipulate($newElems) ,{isAnimated: false},
function(){$newElems.fadeIn('slow');} );
Problem solved!

Infinite Scroll + Swipe.js

Background:
I'm making a portfolio site utilising both Swipe.js and Infinite Ajax Scroll (JQ).
Problem:
When the content from extra pages is loaded into the current page, it is not processed by the already-loaded Swipe.js script. This means that the new content doesn't have it's mark-up changed (needed for the swipe functionality to work).
I think I need to get the Swipe.js script to fire after each page re-load. Would that fix it? Please explain this to me like I'm an 8yr old. JS is not a strong suit...
Demo:
http://hatchcreative.co.nz/tomo
You can see that as the page loads new content, the buttons on either side of the sliders no longer work.
Yes you're right, after the images are loaded you have to create a new Swipe instance on these new elements (as they weren't there at the beginning, when the page was loaded).
Based on the docs of infinite scroll you can use onRenderComplete.
So you had your jQuery.ias constructor like this:
jQuery.ias({
// ... your settings...
onRenderComplete: function(items) {
$(items).each(function(index, element) {
new Swipe(element);
});
}
});
This should work this way somehow, but I am not exactly sure; I haven't worked with these libraries yet.
Edit:
After some more inspection of your code, I saw you had some inline click handler like: onclick='two.prev();return false;'.
You need to remove this and add your onclick handle in the same onRenderComplete function.
onRenderComplete: function(items) {
var swipe;
$(items).each(function(index, element) {
swipe = new Swipe(element);
});
// find tags with the class 'forward' inside the current element and add the handler
$(element).find('.forward').on('click', function() {
swipe.next();
});
// ... also for previous
}
By the way: Usually you should provide a jsFiddle with your important code parts, so it's easier for us to get the problem, and the question is not getting obsolote when the linked page changes.

How can I scroll to a page element in jQuery Mobile?

I have a long jQuery mobile page and would like to scroll to an element halfway down this page after the page loads.
So far I've tried a few things, the most successful being:
jQuery(document).bind("mobileinit", function() {
var target;
// if there's an element with id 'current_user'
if ($("#current_user").length > 0) {
// find this element's offset position
target = $("#current_user").get(0).offsetTop;
// scroll the page to that position
return $.mobile.silentScroll(target);
}
});
This works but then the page position is reset when the DOM is fully loaded. Can anyone suggest a better approach?
Thanks
A bit late, but I think I have a reliable solution with no need for setTimeout(). After a quick look into the code, it seems that JQM 1.2.0 issues a silentScroll(0) on window.load for chromeless viewport on iOS. See jquery.mobile-1.2.0.js, line 9145:
// window load event
// hide iOS browser chrome on load
$window.load( $.mobile.silentScroll );
What happens is that this conflicts with applicative calls to silentScroll(). Called too early, the framework scrolls back to top. Called too late, the UI flashes.
The solution is to bind a one-shot handler to the 'silentscroll' event that calls window.scrollTo() directly (silentScroll() is little more than an asynchronous window.scrollTo() anyway). That way, we capture the first JQM-issued silentScroll(0) and scroll to our position immediately.
For example, here is the code I use for deep linking to named elements (be sure to disable ajax load on inbound links with data-ajax="false"). Known anchor names are #unread and #p<ID>. The header is fixed and uses the #header ID.
$(document).bind('pageshow',function(e) {
var $anchor;
console.log("location.hash="+location.hash);
if (location.hash == "#unread" || location.hash.substr(0,2) == "#p") {
// Use anchor name as ID for the element to scroll to.
$anchor = $(location.hash);
}
if ($anchor) {
// Get y pos of anchor element.
var pos = $anchor.offset().top;
// Our header is fixed so offset pos by height.
pos -= $('#header').outerHeight();
// Don't use silentScroll() as it interferes with the automatic
// silentScroll(0) call done by JQM on page load. Instead, register
// a one-shot 'silentscroll' handler that performs a plain
// window.scrollTo() afterward.
$(document).bind('silentscroll',function(e,data) {
$(this).unbind(e);
window.scrollTo(0, pos);
});
}
});
No more UI flashes, and it seems to work reliably.
The event you're looking for is "pageshow".
I was digging a lot this issue, also at jQuery mobile official forum.
Currently it seems that there is no solution (at least for me).
I tried different events (mobileinit, pageshow) and different functions (silentscroll, scrolltop) as suggested above, but, as a result, I always have page scrolled until all images and html is finished loading, when page is scrolled to top again!
Partial and not really efficient solution is using a timer as suggested in comment to sgliser's answer; unfortunately with a timeout is difficult to know when page will be fully loaded and if scroll happened before that, it will scroll back to top at the end of load, while if it happens too long after page has fully loaded, the user is already scrolling page manually, and further automated scroll will create confusion.
Additionally, would be useful to have silentscroll or other function to address a specific id or class and not plain pixels, because with different browsers, resolutions and devices it may give different and not correct positioning of the scroll.
Hope someone will find a smarter and more efficient solution than this.

Categories

Resources