Anchoring To The Same Page
I wanted to point to a portion in the same page. So used the anchor method. But the problem is, I have a static navigational bar at the top. So the heading of the section goes belo
Solution 1:
I would do the scrolling using jQuery and changing the anchors in the URL to elements that don't exist on the DOM with the same value for id
or name
. (so that the scroll is not done automatically)
$(window).on('hashchange',function(){
//you can see it manually or calculate it using jQuery by using $.height();var header = 60;
//Getting the anchor and replacing the underscorevar value = window.location.hash.replace('_', '');
//getting our destination var dest = $(value).position();
//if the element exist on the DOMif(typeof dest !== "undefined"){
var dtop = dest.top;
//proceeding to scroll
$('html, body').animate({
scrollTop: dtop - header
}, 1000);
}
});
The links in my example look like #_link1
and the id needed to appear in the DOM should be like id="link1
:
<divid="menu"><ahref="#_link1">Link 1</a><ahref="#_link2">Link 2</a><ahref="#_link3">Link 3</a></div>
...
<h1id="link1>Link 1</h1>
Of course, you can change the underscore (_
) on the URL for any other character or symbol you want. Just make sure to replace it for an empty string on the replace
statement of the code I provided.
Post a Comment for "Anchoring To The Same Page"