I'm trying to develop an infinet scroll with javascript and laravel but I'm finding that the javascript function when the scroll reaches the end is triggered multiple times, which makes it not work correctly.
The javascript code is this:
<script type="text/javascript">
window.onscroll = function(ev) {
if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight) {
window.livewire.emit('load-more');
console.log('load more');
}
};
</script>
Any idea why this is happening?
You need to add a flag used to disable loading. Here we add a boolean isLoading
to the window object:
<script type="text/javascript">
window.isLoading = false
window.onscroll = ev => {
// Check scroll position
if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight) {
// Check loading flag
if(window.isLoading){
console.log('still loading');
return true
}
// Load more data
window.livewire.emit('load-more');
console.log('load more');
// Set the flag to disable loading
window.isLoading = true;
}
};
// To reset the isLoading flag we'll emit an event from the Livewire component to the browser
window.addEventListener('loading-complete', event => {
console.log('loading complete');
window.isLoading = false;
})
</script>
As you can see above we reset the isLoading
flag by emitting an event to the browser from the Livewire component (see the docs):
public function loadData()
{
// Load data
// Dispatch event to frontend
$this->dispatchBrowserEvent('loading-complete');
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments