BgColor for selected option on the menu

Issue

I have this prewritten code from w3schools.com and I’m struggling to give a background color to a selected option. Meaning, that by pressing on one of the options, the browser navigates to the page chosen, then on the destination page, I want that option to be highlighted to represent the page shown by giving it a special background color.

    .navbar {
      overflow: hidden;
      background-color: #333;
      position: fixed;
      top: 0;
      width: 100%;
    }
    
    .navbar a {
      float: left;
      display: block;
      color: #f2f2f2;
      text-align: center;
      padding: 14px 16px;
      text-decoration: none;
      font-size: 17px;
    }
    
    .navbar a:hover {
      background: #ddd;
      color: black;
    }
<div class="navbar">
  <a href="#home">Home</a>
  <a href="#news">News</a>
  <a href="#contact">Contact</a>
</div>

Solution

For this you can use a class class="active" to control with link you want to highlight from the others. You just need send to the destination page a flag or a var that indicate what link need to be active. Here a littler example.

    .navbar {
      overflow: hidden;
      background-color: #333;
      position: fixed;
      top: 0;
      width: 100%;
    }
    
    .navbar a {
      float: left;
      display: block;
      color: #f2f2f2;
      text-align: center;
      padding: 14px 16px;
      text-decoration: none;
      font-size: 17px;
    }
    
    .navbar a:hover {
      background: #ddd;
      color: black;
    }
    .navbar a.active {
      background: white;
      color: black;
    }
<div class="navbar">
  <a href="#home" >Home</a>
  <a href="#news" class="active">News</a>
  <a href="#contact">Contact</a>
</div>

Answered By – Alfonso Rodriguez

Answer Checked By – Gilberto Lyons (AngularFixing Admin)

Leave a Reply

Your email address will not be published.