I use a position:fixed menu at http://communitychessclub.com/index.php to keep the menu on screen even as the user scrolls:
CSS:
#sticky {margin:0 auto; display:table}
#sticky.stick {position: fixed; top: 0; margin-left:48px; z-index: 10000; }
JS:
<script>
function sticky_relocate() {
var window_top = $(window).scrollTop();
var div_top = $('#sticky-anchor').offset().top;
if (window_top > div_top)
$('#sticky').addClass('stick')
else
$('#sticky').removeClass('stick');
}
$(function() {
$(window).scroll(sticky_relocate);
sticky_relocate();
});
$(window).scroll((function() {
var a='', // a buffer to the hash
w = $(window);
return function() {
var h = location.hash;
// if hash is different from the previous one, which indicates
// the hash changed by user, then scroll the window down
// update the buffer
if (h != a) {
a = h;
w.scrollTop(w.scrollTop()-150)
}
};
})());
</script>
But people complain that to link to an ID on the same page causes the screen to abruptly scroll. So I found “Improving User Experience With jQuery Smooth Page Anchor Transitions” at http://www.spydertrap.com/blog/2012/08/user-experience-jquery-smooth-page-anchor-transitions/ and liked the demo. Liked it so much that I want to blend the jquery code below with the jquery code above for a smooth jquery scroll.
They use this (but other versions exist here… problem is how to join the two)
jQuery Code:
function goToByScroll(id){
$('html,body').animate({scrollTop: $(id).offset().top},'slow');
}
HTML:
<ul class="nav">
<li><a href="#chapter1">Chapter 1</a></li>
<li><a href="#chapter2">Chapter 2</a></li>
<li><a href="#chapter3">Chapter 3</a></li>
</ul>
JS launcher:
$(document).ready(function(){
$('.nav a').click(function(){
goToByScroll($(this).attr('href'));
return false;
});
});
Is this possible to unite with the jquery code above?
I just tried this by hacking on your page through the chrome browser’s JS console. I added the function
goToByScrollverbatim and then executed this:And sure enough, it scrolls between anchor IDs. There is a minor problem of an exception being thrown when you click on links in your nav bar that aren’t actual anchor links (e.g. ‘Home’ points to the home page, and ‘Chess Camp’ opens a popup). So you could add a class to the anchor links that you want to have scrolling and then add that class to the selector.
For example, modify your markup for the sticky menu bar to look like this:
(added
class="anchor"to all the links that pointing to a hash on the same page.)And add this to your javascript:
That should work for you without throwing any errors.