Reynish
Reynish

Reputation: 140

Using .offset().top to find Elements position on page

I have a DIV I want to scroll with the page but it's not visible above the fold so I'm using this.

$(window).scroll(function() {
    // Get scrolling position of document   
    var scrollYpos = $(document).scrollTop();

    // if its more than the top of the element
    if (scrollYpos > 551 ) {

         // Add a margin to the top 
         $('#scrollingDiv').animate({'margin-top': scrollYpos - 541 }, {duration: 300, queue: false});
    } else {
         $('#scrollingDiv').animate({'margin-top': 0 }, {duration: 200, queue: false});
    }}); // end scroll

ATM I'm giving it the vertical position of the DIV manually (551px). I want to do it dynamically.

var elYpos = $('#scrollingDiv').offset().top

So this finds the vertical position of the element on the page but when the element moves this changes which screws the rest up.

How can i get the position of the element once?

Upvotes: 1

Views: 18793

Answers (1)

Marcis
Marcis

Reputation: 4617

Defined your variable before the function so it's taken only once.

$(function(){
  var elYpos = $('#scrollingDiv').offset().top; // elYpos variable will stay as it's defined
  $(window).scroll(function(){
    var scrollYpos = $(document).scrollTop();
    if (scrollYpos > elYpos ) {
    // and rest of tour code...
  });
});

Upvotes: 6

Related Questions