0

I've got a floating navigation bar at the top of my website and I'm using the following code to scroll to various div anchor points.

<script type="text/javascript">
$(document).ready(function () {
$('a[href^="#"]').on('click', function (e) {
    e.preventDefault();

    var target = this.hash,
        $target = $(target);

    $('html, body').stop().animate({
        'scrollTop': $target.offset().top - 100 // floatnav height
    }, 900, 'swing', function () {
        window.location.hash = '1' + target;
    });
});
});
</script>

I'd like to be able to make the offset different depending on the anchor. Some of them are full page images that don't need an offset as nothing is really lost behind the navigation bar, whereas some start with text so the navigation bar needs to sit above them so that it does not hide content.

Joel
  • 4,732
  • 9
  • 39
  • 54
Chris Traverse
  • 113
  • 1
  • 10

1 Answers1

0

You could store the offset for each section in an attribute on the destination anchor, like:

<a name="example" data-offset="100">Example</a>

You can then access this attribute from within the click handler as follows:

var offset = $(target).attr('data-offset')

Then all you need to do is subtract the additional offset from the element's offset.

athms
  • 948
  • 5
  • 8
  • I'm not exactly sure where to put var offset = $(target).attr('data-offset') in the above code to get it to work. – Chris Traverse Jul 02 '14 at 15:26
  • @ChrisTraverse just after you define $target will be fine. Then you can subtract offset like so within the jQuery animate method: $target.offset().top - offset – athms Jul 02 '14 at 15:31
  • This is what I thought, but it doesn't seem to work. Just so I know we're both on the same wavelength here's the code with your additions, and the default offset set to zero. Each one links to zero, despite the second link having a manual offset of 100. http://jsfiddle.net/56pLq/ – Chris Traverse Jul 02 '14 at 15:45
  • The JSFiddle had a few issues - I've tidied it up, included jQuery and added the offset subtraction: http://jsfiddle.net/56pLq/1/ – athms Jul 02 '14 at 15:54