I wish to update the fragment identifier on the url as the user is scrolling so that it matches the element at the top of the screen.
Is there a way to do that?
I wish to update the fragment identifier on the url as the user is scrolling so that it matches the element at the top of the screen.
Is there a way to do that?
I think this is what you want: http://fiddle.jshell.net/hainawa/u5e2s/show/light/
HTML:
<div id="section-1" class="section">section-1 <br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /></div>
<div id="section-2" class="section">section-2 <br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /></div>
<div id="section-3" class="section">section-3 <br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /></div>
<div id="section-4" class="section">section-4 <br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /></div>
JavaScript(rely on jQuery):
$(function() {
var $secitions = $(".section"),
topArrays = {};
$secitions.each(function(i, ele) {
var $section = $secitions.eq(i),
secTop = $section.offset().top;
topArrays[secTop] = $section.attr("id");
});
$(document,window).scroll(function(e) {
var $ele = $(e.currentTarget),
currentTop = $ele.scrollTop(),
currentHash, arrayHash, topDiff;
for(var i in topArrays) {
arrayHash = topArrays[i];
topDiff = currentTop - i;
currentHash = document.location.hash;
//It's impossable to scroll to the section without any offset
if(topDiff > 0 && topDiff < 100 && currentHash != arrayHash) {
document.location.hash = arrayHash;
}
}
});
});
But there are some problems here:
If anyone has better solution,I'll be grateful,cause I've been thinking about it for a long time.