Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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: 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");
    }
});​
like image 355
rex Avatar asked Sep 19 '12 20:09

rex


1 Answers

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");
    }
});​

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.

like image 107
j08691 Avatar answered Oct 29 '22 20:10

j08691