0

I am trying to make a navbar so that when you are on the page lets say "Home" - the link of "home" on the navbar highlights blue therefore when you are on a different page it is no longer blue. I am doing this in a ruby on rails app so I need to use javascript in order for this to happen. Below is the HTML for the navbar as well as the javascript that I am trying to use.

Navbar HTML

<div class="navbar-box d-flex">
  <div class="logo-box"></div>
  <div class="links d-flex justify-content-around align-items-center">
    <a><%= link_to "HOME", root_path %></a>
    <a><%= link_to "ABOUT US", about_path %></a>
    <a><%= link_to "APARTMENTS", index_path %></a>
    <a><%= link_to "CONTACT US", new_contact_path %></a>
  </div>
</div>

Javascript

const currentLocation = window.location.href
const menuItem = document.querySelectorAll('a');
const menuLength = menuItem.length;
for(let i = 0; i < menuLength; i++){
  if(menuItem[i].href === currentLocation){
    menuItem[i].className = "active"
  }
}

CSS

.active{
  color: #7587bf

}
Barmar
  • 741,623
  • 53
  • 500
  • 612

0 Answers0