I have a single page website and I am using an ACTIVE class on the nav to highlight the links in the NAV.
The javascript to make nav links active:
$(document).ready(function () {
$('.inner-nav li a').click(function(e) {
$('.inner-nav li.active').removeClass('active');
var $parent = $(this).parent();
$parent.addClass('active');
e.preventDefault();
});
});
window.onscroll = () => {
var current = "parent";
sections.forEach((page-section) => {
const sectionTop = section.offsetTop;
if (pageYOffset >= sectionTop ) {
current = section.getAttribute("main"); }
});
navLi.forEach((li) => {
li.classList.remove("active");
if (li.classList.contains(current)) {
li.classList.add("active");
}
});
};
The NAV html:
<div class="inner-nav desktop-nav">
<ul class="clearlist scroll-nav local-scroll">
<li class="active"><a href="#home" onclick="ChangeUrl('Home', '/');">Home</a></li>
<li><a href="#about" onclick="ChangeUrl('About', '/about');">About</a></li>
<li><a href="#features" onclick="ChangeUrl('Features', '/features');">Features</a></li>
<li><a href="#news" onclick="ChangeUrl('Blog', '/blog');">Blog</a></li>
<li><a href="#mail-list" onclick="ChangeUrl('Newsletter', '/newsletter');">Newsletter</a></li>
</ul>
</div>
Here is the js for the pushState.
function ChangeUrl(title, url) {
if (typeof (history.pushState) != "undefined") {
var obj = { Title: title, Url: url };
history.pushState(obj, obj.Title, obj.Url);
} else {
alert("Browser does not support HTML5.");
}
}
I am trying to make it to where when you scroll down the pushState will change the URL in the address bar, to match the section it is in.
For example:
If I click on About in the nav it highlights About, and adds /about to the end of the URL.
But when I scroll down to the About section, the About link highlights but doesn't add the /about to the URL in the address bar.
Is there any JS magic that can make this work?
I ended up figuring it out, if anyone else is looking to do this, here you go.
I created a new js file and included it under the jQuery, I noticed it also requires the onScroll so,