JCHASE11
JCHASE11

Reputation: 3941

Using jQuery to calculate offset in an absolutely positioned container

All of my content is within an absolute container, #content, which is 100% width and height. So when scrolling, we are scrolling through the container, not the body.

I am trying to caclulate the offset of a series of sections within the page like so:

$('.advance').on("click", function(){
     var nextSection = $(this).parent('.section').next('.section');

     var nextDistanceTop = nextSection.offset().top - 25;

     $("#content").animate({ scrollTop: nextDistanceTop });
});

Because the container is absolutely positioned, the offset().top is giving me the offset from the top of the viewport. I need to calculate the offset relative to the top of the screen/header, or the scroll position. Any other workarounds to accomplish this?

Here is an example: http://jsfiddle.net/pkxDY/6/

Upvotes: 0

Views: 2201

Answers (1)

Andre Figueiredo
Andre Figueiredo

Reputation: 13425

Use own jQuery scrollTop method:

$('.advance').on("click", function(){
   var nextSection = $(this).parent().next();
   var nextDistanceTop = nextSection.offset().top + $("#content").scrollTop();
   $("#content").animate({ scrollTop: nextDistanceTop });
});

Upvotes: 2

Related Questions