I am trying to grab the ID of each element as they become visible in the viewport on scroll.
The code below works, but I would essentially like to show only one unique ID from the next element that becomes visible, instead of showing as many as visible IDs depending on how many there are in the viewport at the time.
Currently, if we have element A,B,C,D. As soon as B becomes visible, console will return ID of B, but A as well as long as it's visible in the viewport.
Any idea how this could be achieved?
Thanks in advance.
$(window).scroll(function() {
var windscroll = $(window).scrollTop();
var offsetTop = $('.item').offset().top;
$('.item').each(function(i) {
if ($(this).position().top - offsetTop <= windscroll) {
var data = $(this).attr("id");
console.log(data)
}
});
}).scroll();
CodePudding user response:
By using some code from this post, we can modify you code so you will get the last element that is in viewport. I believe this is what you want.
$(window).scroll(function() {
var lastElem = null;
$('.item').each(function(i) {
if ($(this).isInViewport()) {
lastElem = $(this)
}
});
if (lastElem != null) {
console.clear();
console.log(lastElem.attr("id"))
}
}).scroll();
Demo
$.fn.isInViewport = function() {
var elementTop = $(this).offset().top;
var elementBottom = elementTop $(this).outerHeight();
var viewportTop = $(window).scrollTop();
var viewportBottom = viewportTop $(window).height();
return elementBottom > viewportTop && elementTop < viewportBottom;
};
$(window).scroll(function() {
var lastElem = null;
$('.item').each(function(i) {
if ($(this).isInViewport()) {
lastElem = $(this)
}
});
if (lastElem != null) {
console.clear();
console.log(lastElem.attr("id"))
}
}).scroll();
* {
padding: 0;
margin: 0;
}
.item {
height: 120vh;
width: 100%;
border: 1px solid black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="A">A</div>
<div id="B">B</div>
<div id="C">C</div>
<div id="D">D</div>