Update location hash when user scrolls to section
Just as another idea, updating the hash by taking the scroll value is more robust. Can be done in jQuery using scrollTop()
.
$(window).scroll(
function(){
if($(this).scrollTop() > 100 && $(this).scrollTop() < 200){
window.location.hash = "your_hash_name";
}else{
window.location.hash = "";
}
}
);
This updates the location.hash
value once you scroll between (100, 200)
pixels.
Look at my proposition. jQuery code will catch all <section>
selectors after document loaded and set appropriate hash from data-hash
attribute while you scroll.
$(document).ready(function(){
var sections = {};
$(".section").each(function(){
var hash = $(this).data("hash"),
topOffset = $(this).offset().top;
sections[topOffset] = hash;
});
$(window).scroll(function(e){
var scrollTop = $(window).scrollTop();
setHash(scrollTop);
});
function setHash(st){
var hash = "";
for(section in sections){
if (section < st + ($(window).height()/2)) hash = sections[section];
}
console.log(`SETTING HASH: ${hash}`);
window.location.hash = hash;
}
});
section{
position: relative;
display: block;
width: 100%;
height: 800px;
background: #fff;
border-bottom: 1px solid #000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section class="section" data-hash="about">
#about
</section>
<section class="section" data-hash="works">
#works
</section>
<section class="section" data-hash="contact">
#contact
</section>