I am trying to make an infinite scroll effect by using jquery, ajax and html files that I created and uploaded to a cloud storage. I am a beginner and just started learning coding.
** Below is part of the code that I am experimenting with. When I use the current code I have the content is duplicated unless I add $(window).off("scroll.once"); to stop the function from repeating.
*** CURRENTLY *** - The scroll event requires you to reach the bottom of the page, then an ajax request is made and it pulls the content from the html document I uploaded to my cloud drive.
After appending the content of the html file to the Main Tag, if I scroll back to the bottom the page, the function & ajax call is repeated and the content of the html file is duplicated.
*** GOAL *** - Each time the function is completed, I want the url to automatically updated so that the content of the next html file in my cloud storage can be appended below the previous content. I also need to be able to tell the function, how many times to updated the url and reinitialize.
URL Examples for 3 different files:
1st HTML file URL - Anywebsite.com/HTMLl
2nd HTML file URL - Anywebsite.com/HTML2
2nd HTML file URL - Anywebsite.com/HTML3
$(window).on("scroll.once", function() {
if ($(window).scrollTop() == $(document).height()-$(window).height()){
$.ajax({
url: "ENTER FIRST URL",
success: function (data) { $('main').append(data); },
dataType: 'html'
});
}
});
<main>Test</main>
CodePudding user response:
If you have the the html file names numbered per your question then you can use following code to achieve your desired results. Be noted that this is just to give you the idea how to change the url, the code will start given error when it reaches number no html file exist i.e for html4 you'll get 404 response if it does not exist on the location.
var step = 1;
$(window).on("scroll.once", function() {
if ($(window).scrollTop() == $(document).height()-$(window).height()){
$.ajax({
url: 'Anywebsite.com/HTML' step,
success: function (data) { step ; $('main').append(data); },
dataType: 'html'
});
}
});