I have a jQuery code from w3schools.com that changes the URL's #id and enables smooth scrolling to a specific DIV section when clicking an <a href="#id"></a>
. However, it does not work on scroll. I am looking for a solution where the URL's #id changes as I scroll up or down to a particular section.
Here is the current jQuery Code:
$(document).ready(function(){
$("#navlist a").on('click', function(event) {
if(this.hash !== ""){
var hash = this.hash;
$('html, body').animate({
scrollTop: $(hash).offset().top
}, 800, function(){
window.location.hash = hash;
});
}
});
});
I found something on stackoverflow that seems to address the scrolling issue:
$(document).bind('scroll',function(e){
$('div').each(function(){
if ($(this).offset().top < window.pageYOffset + 10 && $(this).offset().top + $(this).height() > window.pageYOffset + 10){
window.location.hash = $(this).attr('id');
}
});
});
While this seems to work independently, combining both codes causes one of them to stop functioning. I would like to merge them to achieve both onclick and scroll effects, but my knowledge of jquery is limited.
For example, a URL with ID:
http://localhost/sites/fh/index.php#first
Any help provided will be greatly appreciated. Thank you!