Jquery Get Element's Top Offset While Scrolling

html, jquery

Solution

Try like this:

if ($(this).offset().top >= $top + $(window).scrollTop()) {

Problem

I want to display Iphone contact list style list on the mobile screen. Basically, while scrolling, header will be first visible item's first letter. For Example: if first visible item is 'Adidas', header will be 'A': I created an ul and lots of li in it: ``` <ul class="onlineShopList"> <li class="activeRow"> <span class="left">A1</span> <span class="right">12 Articles</span> <span class="clear">&nbsp;</span> </li> <li class="normalRow"> <span class="left">A2</span> <span class="right">18 Articles</span> <span class="clear">&nbsp;</span> </li> <li class="activeRow"> <span class="left">A3</span> <span class="right">243 Articles</span> <span class="clear">&nbsp;</span> </li> <li class="normalRow"> <span class="left">B1</span> <span class="right">191 Articles</span> <span class="clear">&nbsp;</span> </li> <li class="activeRow"> <span class="left">B2</span> <span class="right">12 Articles</span> <span class="clear">&nbsp;</span> </li> <li class="normalRow"> <span class="left">B3</span> <span class="right">18 Articles</span> <span class="clear">&nbsp;</span> </li> <li class="activeRow"> <span class="left">C1</span> <span class="right">243 Articles</span> <span class="clear">&nbsp;</span> </li> <li class="normalRow"> <span class="left">C2</span> <span class="right">150 Articles</span> <span class="clear">&nbsp;</span> </li> <li class="activeRow"> <span class="left">C3</span> <span class="right">1 Articles</span> <span class="clear">&nbsp;</span> </li> </ul> ``` it is very simple, and here is the jquery function in order to handle scrolling and change the header: ``` $(window).scroll(function() { $top = $('.onlineShopList').offset().top; /*console.log("item: " + $('.onlineShopList li:first:visible').find('span.left').text()) $('#headChar').text($('.onlineShopList li:first:visible').find('span.left').text().charAt(0));*/ $('.onlineShopList li').each(function() { console.log("current item top : " + $(this).offset().top) if ($(this).offset().top >= $top) { console.log("top char: " + $(this).find('span.left').text().charAt(0)) $('#headChar').text($(this).find('span.left').text().charAt(0)); return false; // stops the iteration after the first one on screen } }); }); ``` But header always A, I couldn't figure out this. Top Offset of first item doesn't change while scrolling, Maybe this method is wrong. Please Help!

Original source