0

I'm looking to achieve the effect of clicking an anchor tag and it scrolling to element on the page.

I already have this with jquery scrollTo. Like so:

$.scrollTo( this.hash, 1500, {
    easing:'easeInOutCubic',
    'axis':'y'
});

However, I need to it align it so that the element sits at the bottom of the viewport when it's finished animating. Each section on the page is a different height so it would need to dynamically get the elements position and height I guess.

I'm having difficulty working out what numbers I need to calculate to achieve this.

EDIT

I have changed it to this now

var section = $(this.hash);

var scrollPos = $(section).offset().top + ( $(window).height() - $(section).height() );

$('html, body').scrollTop( scrollPos );

But this is still wrong, the '#about' section is now halfway up the page on click, rather than aligned at the bottom of the viewport.

Thanks

Chris Till
  • 1,723
  • 6
  • 28
  • 64

3 Answers3

7
  1. get height of the element $(element).height()

  2. get viewport's height $(window).height()

  3. get top position of the element $(element).offset().top

  4. scroll page to $(element).offset().top - ( $(window).height() - $(element).height() )

kbariotis
  • 756
  • 1
  • 13
  • 24
1

Try like this:

var section = $(this.hash);
var scrollPos = section.offset().top + section.height() - $(window).height();

DEMO

Wilmer
  • 2,451
  • 1
  • 11
  • 8
0

there is answer Here that shows how to scroll page so that the selected element aligns to the top of window.

as for your request to align it to the bottom, i have corrected the code from the linked post:

all you have to do basically is to subtract the window height, and the element height as follows:

$('html, body').animate({
    scrollTop: $("#wmd-input").offset().top - $("#wmd-input").height() - $(window).height()
}, 2000)

the #wmd-input element from my example is the answer text area from this page, open developer console in your browser, paste the code and see it in work

(or any other question where you have the answer area available)

Community
  • 1
  • 1
Banana
  • 7,309
  • 3
  • 19
  • 41