1

I'm using JQuery to smooth scroll images:

function smoothScrollTo(hash) {
    $("html:not(:animated).,body:not(:animated)").animate({
        scrollTop: $(hash).offset().top
    }, 650, function () {
        location.hash = hash;
    });
}
$(function () {
    $("#content-images li a[href*=#]").click(function () {
        this.blur();
        smoothScrollTo(this.hash);
        return false;
    });
});

It's working fine however I have a fixed nav bar on the site which stays on the top of the page as it scrolls. When the page scrolls down to the next image, it scrolls underneath the nav bar obscuring apart of it from vision.

My question is, how can I modify the above code to compensate for the height of my fixed nav bar?

Any help would be much appreciated,

T

Abdul Munim
  • 18,869
  • 8
  • 52
  • 61
Tud
  • 11
  • 1
  • 2

2 Answers2

0

Change:

scrollTop: $(hash).offset().top

to:

scrollTop: $(hash).offset().top + $('#fixed_nav_bar').outerHeight()

That should take into account that fixed nav bar height.

Hope that helps :)

will
  • 4,557
  • 6
  • 32
  • 33
  • Many thanks! It does work, however what seems to happen now is that it smooth scrolls down then once it reaches the element it will quickly offset the height causing the page to jump up to the correct position, in turn not making it very smooth anymore. Is there a solution for this? – Tud Oct 27 '11 at 12:23
  • That's because of the animation callback changing the location.hash, which is the same as clicking the link. Give me a sec, I have had to deal with this recently. **Edit:** Actually, that wouldn't work, however, try this out: http://stackoverflow.com/questions/1489624/modifying-document-location-hash-without-page-scrolling – will Oct 27 '11 at 12:32
  • Thanks! Had a read and can't seem to get it working, it just creates a bug where you cannot scroll down anymore after clicking the image. Is there way to just remove the location.hash callback in this instance? – Tud Oct 27 '11 at 13:46
0

Using will's answer, try this:

function smoothScrollTo(hash, t) { // two params
    $("html:not(:animated).,body:not(:animated)").animate({
        scrollTop: $(hash).offset().top + $('#fixed_nav_bar').outerHeight()
    }, 650, function () {
        var tmp = t.id; // hold the id
        t.id = '';      // remove it so we don't jump
        location.hash = hash;
        t.id = tmp;     // now that we didn't jump we can move it back
    });
}
$(function () {
    $("#content-images li a[href*=#]").click(function () {
        this.blur();
        smoothScrollTo(this.hash, this); // two args
        return false;
    });
});
qwertymk
  • 34,200
  • 28
  • 121
  • 184
  • Many thanks! Just tested it and made further observations to both your code and will's, it seems that it just isn't taking the header height into account. The image still scrolls to the top of the browser window (underneath fixed nav) Is there a way for me to manually set the height? – Tud Oct 27 '11 at 15:26