To achieve this you can use filter()
and first()
to retrieve the first .category-title
elements which is next below the current scroll position, then prop()
to get its id:
let $categoryTitles = $('.category-title');
let $output = $('#output span');
$(window).scroll(function() {
let $topCat = $categoryTitles.filter((i, el) => $(el).offset().top > $(window).scrollTop()).first();
$output.text($topCat.prop('id'));
}).scroll();
.category-title {
height: 500px;
border-bottom: 10px solid #C00;
}
#output {
position: fixed;
top: 5px;
left: 100px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="output">Id: <span></span></div>
<div class="category-title" id="A">A</div>
<div class="category-title" id="B">B</div>
<div class="category-title" id="C">C</div>
<div class="category-title" id="D">D</div>
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…