How to get the value of the top div position when scrolling

I try to run some script when the div reaches a certain point while scrolling. There is fixed navigation, and when the user scrolls the window, suppose that it changes the navigation name when it approaches nav. I use the $ (window) .scroll function, but it only checks the position of the div and does not update the value. How to scroll to check the window size every 5-10 pixels so that it does not take up too much memory / processing. The code is set to: http://jsfiddle.net/rexonms/hyMxq/

HTML

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

CSS

#nav {
    height: 50px;
    background-color: #999;
    position:fixed;
    top:0;
    width:100%;

}

#main{
    margin-top:55px;
}
#a, #b, #c {
    height:300px;
    background-color:#ddd;
    margin-bottom:2px;
}

SCRIPT

$(window).scroll(function() {

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

    $('.message').text(b.top);

    if (b.top == 55) {
        $('.message').text("Div B");
    }
});​
+5
source share
1 answer

Try this jsFiddle example

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

div , . , , .

jQuery .position() .offset(). .position() . .offset(), .

+8

All Articles