2

I am building a website which only has a single page, but with different sections, for example, Home, About, Contact etc. I am using anchor tags to scroll through the different sections of the page. I have a fixed navigation menu at the top of the page and I would like to indicate IN the navigation links, which section is active at the moment.

I am learning JavaScript at the moment so I am not sure how to do it. I also want to avoid using jQuery.

MoeLester
  • 31
  • 3

1 Answers1

2

I would use the hashchange event for this. Whenever it fires update your navigation by adding/removing a class. In the following example the class is called "active".

window.addEventListener("hashchange", updateActiveNavigationEntry);

function updateActiveNavigationEntry () {
  // query currently active item
  const currentActiveItem = document.querySelector('#navigation a.active');
  // remove active class
  if (currentActiveItem) currentActiveItem.classList.remove("active");
  // query new active item
  const newActiveItem = document.querySelector('#navigation a[href="'+ window.location.hash +'"]');
  // add active class to new entry
  if (newActiveItem) newActiveItem.classList.add("active");
}
.active {
  background: red;
}
<div id="navigation">
  <a href="#section01">section01</a>
  <a href="#section02">section02</a>
  <a href="#section03">section03</a>
</div>
Robbendebiene
  • 4,215
  • 3
  • 28
  • 35