Reputation: 1345
I need to check if the user has scrolled to the end of a list item <li>
on my page. I want to perform an AJAX call, when this happens.
How to know if the user has scrolled to the last list item.
This is what I've tried till now.
if ($('li:last').is(':visible')) {
alert('Scrolled to last li');
}
But, unfortunately it is not working.
Upvotes: 1
Views: 2319
Reputation: 87233
You cannot check if the element is visible
, because even if the element is not in the viewport it is still visible.
From jQuery Docs:
Elements are considered visible if they consume space in the document. Visible elements have a width or height that is greater than zero.
Tweaked my other answer little bit.
$(document).ready(function() {
// Get window height, and the bottom of the viewport
var windowHeight = $(window).height(),
gridTop = windowHeight * .1,
gridBottom = windowHeight + $('ul li:last').height();
// On each scroll event on window
$(window).on('scroll', function() {
// Interested element caching
var $lastElement = $('ul li:last');
// Get elemets top
var thisTop = $lastElement.offset().top - $(window).scrollTop();
// Check if the element is in the current viewport
if (thisTop > gridTop && (thisTop + $lastElement.height()) < gridBottom) {
$('#message').text('Yay! In sight');
$lastElement.addClass('middleviewport');
} else {
$('#message').text('Still not available');
$lastElement.removeClass('middleviewport');
}
});
});
#message {
position: fixed;
top: 0;
text-align: center;
z-index: 2;
background: yellow;
padding: 10px;
width: 100%;
color: red;
}
ul {
margin: auto;
}
ul li {
width: 300px;
height: 10px;
background: #f5f5f5;
float: left;
margin: 10px;
}
ul li.middleviewport {
background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<div id="message">Still not available</div>
<ul>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
Upvotes: 1
Reputation: 3757
You can use a function like this:
function isElementVisible(elem)
{
var $elem = $(elem);
var $window = $(window);
var docViewTop = $window.scrollTop();
var docViewBottom = docViewTop + $window.height();
var elemTop = $elem.offset().top;
var elemBottom = elemTop + $elem.height();
return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));
}
And handle the scroll event:
$(document).ready(function(){
$(window).scroll(function(){
var e = $('#yourContiner ul li:last');
if (isElementVisible(e)) {
alert('visible');
}
})
})
Upvotes: 1