HTML5 + jQuery + Infinite Scroll
-
27-10-2019 - |
Question
After much research, I have learned that binding
the scroll
event to the $(window)
in the live
state is not supported. This is fine, but I do have a question or two in regards to the script I am working on.
I have a website that is utilizing the HTML5 jQuery History Plugin (http://tkyk.github.com/jquery-history-plugin/) to load in pages for a fluid user experience since my site has an anchored audio player within it.
On one of my pages I have created an infinite scroll to load in Albums upon the window scroll. It works fine if you go to the page directly, but if you go there via an HTML5 enabled link (I have some links that are specifically for the HTML5 implementation) it doesn't work.
Here is my Infinite Scroll Code:
jQuery(function() {
var getMoreMedias, loading, mediaType, nearBottomofPage, page, pendingCall, genreType, url, did_scroll;
page = 1;
loading = false;
// did_scroll = false
mediaType = $('.breadcrumbs strong').attr('rel');
genreType = $('.breadcrumbs strong').data('genre-id')
nearBottomofPage = function() {
return $(window).scrollTop() > $(document).height() - $(window).height() - $('#footer').height();
};
getMoreMedias = function(page, mediaType) {
opts = {
lines: 12, //The number of lines to draw
length: 7, //The length of each line
width: 3, //The line thickness
radius: 10, //The radius of the inner circle
color: '#000', // #rgb or #rrggbb
speed: 1, //Rounds per second
trail: 60, // Afterglow percentage
shadow: true //Whether to render a shadow
};
var spinner = new Spinner(opts).spin()
$('#loadingMore').append(spinner.el)
url = '/top_medias/'
url += mediaType
if(genreType)
url += '/' + genreType
url += '?page=' + page
$.ajax({
cache: false,
url: url,
type: 'get',
dataType: 'script',
success: function(data) {
$('#loadingMore').html('');
loading = false
},
error: function() {
$('#loadingMore').html('<p>No more results could be found</p>')
loading = false
}
});
};
$(window).scroll(function(){
did_scroll = true
})
setInterval(function(){
if(did_scroll) {
if (loading) return;
if (nearBottomofPage()) {
loading = true;
page++;
getMoreMedias(page, mediaType)
did_scroll = false
}
}
}, 250)
});
Is there any way to take what I have above and make it work if the page is accessed via Ajax (which is what the HTML5 plugin essentially does)?
Solution
I'm not sure if this addresses your problem, but the statement that "it works when browsed but not when Ajax loads it" raised a flag to me - Javascript doesn't execute in Ajax loaded pages, rather you must eval()
evaluate the Javascript.
What I do when I need this functionality is add a hidden <div>
containing Javascript (without the `' tag and execute that after loading, e.g. (psuedo code)
$.ajax(url, success: function() { eval($('#ajax').html(); });
<div id="ajax" style="display:none"> alert('here'); </div>