2

I have a site that uses a fixed menu on the top of the page.

When a link is clicked, it should scroll vertically so that the center of that target div aligns with the vertical center of the window, offset by the height of the header. - this is very important so that the div is centered no matter what the resolution of the monitor is

I'm using jQuery and scrollTo, but can't figure out the math needed for this.

Here's my attempt:

function scrollTo(target) {
var offset;
var scrollSpeed = 600;

if (viewport()["width"] > 767 && !jQuery.browser.mobile) {
    // Offset anchor location and offset navigation bar if navigation is fixed
    offset = $(target).offset().top - document.getElementById('navigation').clientHeight;
} else {
    // Offset anchor location only since navigation bar is now static
    offset = $(target).offset().top;
}

    $('html, body').animate({scrollTop:offset}, scrollSpeed);
}
jwg2s
  • 806
  • 1
  • 12
  • 25
  • I *think* you should align the scrolled-to div to the top of the window, in case you have a div with a height larger than the browser's window, its top won't be cut off. Unless you're sure all divs are <=400px. – Fabrício Matté Jun 05 '12 at 00:48
  • Would be nice if you could post a live demo of your markup in a http://jsfiddle.net for testing as well. – Fabrício Matté Jun 05 '12 at 00:52

2 Answers2

0

Eventually figured it out. Was just being dumb with the math. Offset with the fixed header and footer as well, works for all resolutions.

    // scrollTo: Smooth scrolls to target id
function scrollTo(target) {
    var offset;
    var scrollSpeed = 600;
        var wheight = $(window).height();
        //var targetname = target;
        //var windowheight = $(window).height();
        //var pagecenterH = windowheight/2;
        //var targetheight = document.getElementById(targetname).offsetHeight;

    if (viewport()["width"] > 767 && !jQuery.browser.mobile) {
        // Offset anchor location and offset navigation bar if navigation is fixed
        //offset = $(target).offset().top - document.getElementById('navigation').clientHeight;
                offset = $(target).offset().top - $(window).height() / 2 + document.getElementById('navigation').clientHeight + document.getElementById('footer').clientHeight;
    } else {
        // Offset anchor location only since navigation bar is now static
        offset = $(target).offset().top;
    }

    $('html, body').animate({scrollTop:offset}, scrollSpeed);
}
jwg2s
  • 806
  • 1
  • 12
  • 25
-1

I have done a simple jquery. I think that might help what you are looking for.

Please see demo

The target div stay vertically centre offset header.

Dips
  • 3,220
  • 3
  • 20
  • 21
  • This changes the margin of the div, I need to actually scroll to the div since the page contains numerous divs. – jwg2s Jun 05 '12 at 00:57