I can't get this ajax infinite scroll to work on a touchscreen or mobile cell phone.
I have been trying to calculate the screen size with header, content and footer divs, but nothing works.
How can I trigger a function when I am at the bottom of the page?
Found som examples here, but none of them works.
This is what I have right now, working on a desktop.
Thanks,
<script>
$(window).scroll(function() {
if($(window).scrollTop() $(window).height() >=$(document).height()) {
var last_id = $(".trailerid:last").attr("id");
loadMore(last_id);
}
});
function loadMore(last_id){
$.ajax({
url: 'loadMore.inc.php?lastTrailerId=' last_id,
type: "get",
beforeSend: function(){
$('.ajax-load').show();
}
}).done(function(data){
$('.ajax-load').hide();
$("#trailerData").append(data);
}).fail(function(jqXHR, ajaxOptions, thrownError){
alert('Servern svarar inte...');
});
}
</script>
CodePudding user response:
Look in the the Intersection Observer API. This API is designed to detect whenever certain observed elements come in (and out) of the viewport. It's a more performant alternative than listening to the scroll event.
With the API you could place an element at the bottom of the page, let's call this element the trigger. Whenever this trigger comes into view, call the loadMore
function and add items to the list. The trigger should now be pushed to the bottom and out of view again. Scroll down to repeat this process.
I've made a demo below which uses this technique to simulate an infite scroll effect. It works the same way as described above.
const list = document.querySelector('.list');
const trigger = document.querySelector('.trigger');
const loadMore = () => {
const item = document.createElement('div');
item.className = 'item';
list.append(item);
}
const handleIntersect = entries => {
for (const { isIntersecting } of entries) {
if (isIntersecting) {
loadMore();
}
}
};
const options = {
root: null,
rootMargin: '0px',
treshold: 0
}
const observer = new IntersectionObserver(handleIntersect, options);
observer.observe(trigger);
body {
margin: 0;
padding: 0;
counter-reset: item;
}
.item {
display: grid;
place-content: center;
height: 200vh;
width: 100vw;
background-image: linear-gradient(0deg, transparent, black);
}
.item::before {
counter-increment: item;
content: counter(item);
font-size: 32px;
font-family: sans-serif;
font-weight: bold;
}
<div >
<div ></div>
</div>
<div ></div>