I was wondering how I can change the hash in my URL bar while scrolling to another section. I used the following code to change the menu item class of the visible section in the viewport:
function setActiveListElements(event){ // Get the offset of the window from the top of page var windowPos = $(window).scrollTop();
$('#primary-navwrapper li a[href^="#"]').each(function() {
var anchorId = $(this);
var target = $(anchorId.attr("href"));
//console.log(target);
var offsetTop = target.position().top - offset;
if (target.length > 0) {
if (target.position().top - offset <= windowPos && (target.position().top + target.height() + offset ) > windowPos) {
$('#primary-navwrapper li a').removeClass("current");
anchorId.addClass("current");
}
}
});
}
I have already used a code to update the hash, when the user clicks on a menu item, but doesn’t know how to integrate it inside above code:
$('#primary-navwrapper li, .list-of-links li').find('a[href^="#"]').click(function(event) { // Prevent from default action to intitiate event.preventDefault();
$('#primary-navwrapper li a').removeClass("current");
$(this).addClass("current");
var anchorId = $(this).attr("href");
var target = $(anchorId).offset().top - offset;
//console.log(target);
$('html, body').animate({ scrollTop: target }, 500, function () {
window.location.hash = anchorId;
});
});
In above code I used: window.location.hash = anchorId;