jquery to jump to page anchors - slightly off

Joined
12 Feb 2006
Posts
17,310
Location
Surrey
i currently use jquery to smoothly jump page anchors, however there is a slight issue in that my header section with a height of approx 100px, which is fixed at the top of the page, lays over the top of where the page scrolls to, cover the top 100px.

below is the code I use

JavaScript:
    $(".section_gallery a").click(function() {
        event.preventDefault();
        $('html, body').animate({
            scrollTop: $("#section_gallery").offset().top
        }, 400);
    });

i was hoping that offset() could have parameters to set is 100px lower, but it doesn't appear to work how i had hoped.

any suggestion as to how I can solve this?

many thanks
 
Soldato
Joined
3 Jun 2005
Posts
3,117
Location
The South
Have you tried subtracting the header height (100px) as scrollTop simply takes an integer value? eg -

JavaScript:
$(".section_gallery a").click(function() {
        event.preventDefault();
        $('html, body').animate({
            scrollTop: ($("#section_gallery").offset().top - 100)
        }, 400);
    });

Arguably you could grab the header element height instead of using a fixed value.
 
Soldato
Joined
3 Jun 2005
Posts
3,117
Location
The South
that worked great. how would i get the height of the #header? as this works perfectly, but realised an issue in that the header height changes depending on mobile/desktop viewing, so now it scrolls too high on mobile view

You can either use (both are slightly different so have a quick read) .height() (https://api.jquery.com/height/) or .outerHeight() (https://api.jquery.com/outerheight/) on an element, so you end up with something like -

JavaScript:
$(".section_gallery a").click(function() {
    event.preventDefault();
    $('html, body').animate({
        scrollTop: ($("#section_gallery").offset().top - $(SELECTOR_HERE).outerHeight())
    }, 400);
});
 
Soldato
Joined
26 Sep 2010
Posts
7,201
Location
Stoke-on-Trent
Something else to consider: if the anchor you want to jump to doesn't have a full window's height underneath it, your animation will do a hard jank as the scroll "hits" the bottom of the content. So, when you determine your scroll location, you'll also have to factor in available content after the anchor, and if it's not a full screen height then offset the scroll target to compensate.

As an example, jump on here

And click "Domestic & Commercial sectors" on the left nav. The page doesn't scroll until the actual heading is at the top of the page because there isn't enough content underneath to do so, but the animated scroll remains smooth.

(the actual JS is horribly old now, I've not had the time or inclination to update it without actually getting paid :p)
 
Back
Top Bottom