How to get the div top position value while scrolling

I am trying to run some script when div reaches to a certain point when it's scrolled. There is a fixed navigation and when the user scrolls the window it suppose change the nav name once it reaches close to the nav. I am using the $(window).scroll function but it only checking the div position once and not updating the value. How to make scroll check the window size every 5-10 px move so that it doesn't take too much memory/processing. The code is set up at:


<div id="nav"> NAVIGATION
  <div class="message">div name</div>
<div id="main">
<div id="a">Div A</div>
<div id ="b"> Div B</div>
<div id ="c"> Div C</div>


#nav {
    height: 50px;
    background-color: #999;


#a, #b, #c {


$(window).scroll(function() {

    var b = $('#b').position();


    if ( == 55) {
        $('.message').text("Div B");

Try this jsFiddle example

$(window).scroll(function() {
    var scrollTop = $(window).scrollTop(),
        divOffset = $('#b').offset().top,
        dist = (divOffset - scrollTop);
    if ( == 55) {
        $('.message').text("Div B");

Your original code was only checking the position of the div relative to the top of the document which never changes. You need to calculate in the amount of scroll the window has incurred and calculate accordingly.

Also note the difference beyween jQuery's .position() and .offset() methods. The .position() method allows us to retrieve the current position of an element relative to the offset parent. Contrast this with .offset(), which retrieves the current position relative to the document.