First of all, you do not need to use the old convention <a name= . Check out the w3schools page for HTML anchors on w3schools . Best practice is to bind the container element by id.
So, if you are linking to a div with some content, use <div id="linkToMe">My content in here.</div> and <a href="#linkToMe">The link text</a> .
This, of course, will break your code above as it searches for elements by name. You want to search for them by id (faster anyway!).
On my webpage, I have a toolbar at the top, which is sometimes position: fixed; , so when I scroll, I want to shift the scroll position so that it does not fall under my toolbar at the top of the page.
Here is how I do it:
function goToByScroll(id) { //Find toolbar height var pageOffset = 0, hdr = $('#sub'), tb = $('#sitemenu'); if (hdr.css('position') == 'fixed') { pageOffset += hdr.height() } if (tb.css('position') == 'fixed') { pageOffset += tb.height() } //Scroll the document $('html,body').animate({ scrollTop: $("#" + id).offset().top - pageOffset }, 'slow'); }
and then connect it to jQuery:
$(".jumptoid").click(function (e) { e.preventDefault(); // Track in google analytics if you are using it. _gaq.push(['_trackEvent', 'Jump to Id', e.currentTarget.host, this.href, 0]); // Scroll to item location using jquery goToByScroll(this.href.split('#')[1]); // Push History in browser bar so the forward/back button works window.location.hash = this.href.split('#')[1]; return false; });
This will perfectly align the top of the target element with the bottom of my title / toolbar if they are fixed in position or the top of the browser view if not.
In your case, you either want to change the way the offset is calculated (instead of the hdr and tb elements, you can do some other math or see other elements of the page), or you can use the custom attribute suggested by @chris moutray.
If you want to use the attribute, use the proposed html5 standard, starting with data- , so that it passes the check. For exmaple <div id="linkToMe" data-scroll-offset="250">My content here</div> and then use the @chris code to grab this attribute, like $anchor.attr('data-scroll-offset') .