Modify the CSS to update the navbar's active color

I'm currently using a simple CSS top navbar (without Bootstrap or any other framework) and I want to be able to change the active page's button color. For example, when I navigate to the home page, I want the button in the navbar to turn red or a different color, and the same for other pages...

Here's the code snippet:

body {
  margin: 0;
}

.logo {
  margin: 0;
  padding: 0;
  overflow: hidden;
  background-color: #f2f2f2;
  float: left;
  width: 25%;
}

ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
  overflow: hidden;
  background-color: #333;
}

li {
  float: left;
}

li a {
  display: block;
  color: white;
  text-align: center;
  padding: 14px 40px;
  text-decoration: none;
  font-size: 18px;
}

li a:hover {
  background-color: #111;
}
<ul>
  <li><a href="#">Home</a></li>
  <li><a href="#">News</a></li>
  <li><a href="#">Contact</a></li>
  <li><a href="#">About</a></li>
  <li><a href="#">Division</a></li>
  <li><a href="#">Career</a></li>
  <li><a href="#">MChoice's</a></li>
</ul>

Any ideas on how to achieve this? Would it be okay to incorporate JavaScript?

Thanks in advance!

Answer №1

My approach includes using

$(document).ready(function() {..}
to fetch the path with
var url = window.location.pathname;
. This way, you can determine the link that the user is navigating from, helping you identify the menu item they selected.

Subsequently,

$('ul li a').each(function() {...}
iterates through each menu item. It compares the url path with the href attributes of the menu items. If there is a match, the respective menu item is given the active status by adding a css class. On the contrary, if there is no match, any existing active class is removed. This methodology should effectively serve the purpose.

(Please keep in mind that this scenario assumes your application is not a single-page application.)

For a single-page application, the process is simpler - deactivate all menu items and activate the one that was clicked.

$(document).ready(function() {
  //var url = window.location.pathname;
  var url = 'http://stacksnippets.net/js#division';
  console.log('url-->', url);

  $('ul li a').each(function() {
    var href = $(this).attr('href');
    if (!!url.match(href)) {
      $(this).addClass('active');
    } else {
      $(this).removeClass('active');
    }
  });

});
body {
  margin: 0;
}

.logo {
  margin: 0;
  padding: 0;
  overflow: hidden;
  background-color: #f2f2f2;
  float: left;
  width: 25%;
}

ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
  overflow: hidden;
  background-color: #333;
}

li {
  float: left;
}

li a {
  display: block;
  color: white;
  text-align: center;
  padding: 14px 40px;
  text-decoration: none;
  font-size: 18px;
}

li a:hover {
  background-color: #111;
}

.active {
  background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li><a href="#home">Home</a></li>
  <li><a href="#news">News</a></li>
  <li><a href="#contact">Contact</a></li>
  <li><a href="#about">About</a></li>
  <li><a href="#division">Division</a></li>
  <li><a href="#career">Career</a></li>
  <li><a href="#mchoices">MChoice's</a></li>
</ul>

Answer №2

To easily highlight the current page link, you can simply add an 'active' class to the corresponding link:

<ul>
  <li><a href="#" class="active">Home</a></li>
  <li><a href="#">News</a></li>
  <li><a href="#">Contact</a></li>
  <li><a href="#">About</a></li>
  <li><a href="#">Division</a></li>
  <li><a href="#">Career</a></li>
  <li><a href="#">MChoice's</a></li>
</ul>

Then you can easily style the links with the active class:

li a.active {
    background: #F00;
}

If you are using a content management system (CMS) like Wordpress, the active class is usually applied automatically. However, for static HTML sites, you may need to add the active class manually.

Answer №3

Check out the code below to activate the menu items:

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
   $('li a').on('click', function(){
      $('li a').removeClass('active');
      $(this).addClass('active');
    }); 
});
</script>

<style type="text/css">
body {
  margin: 0;
}

.logo {
  margin: 0;
  padding: 0;
  overflow: hidden;
  background-color: #f2f2f2;
  float: left;
  width: 25%;
}

ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
  overflow: hidden;
  background-color: #333;
}

li {
  float: left;
}

li a {
  display: block;
  color: white;
  text-align: center;
  padding: 14px 40px;
  text-decoration: none;
  font-size: 18px;
}

li a:hover, li a.active {
  background-color: #111;
}

</style>
<ul>
  <li><a href="#">Home</a></li>
  <li><a href="#">News</a></li>
  <li><a href="#">Contact</a></li>
  <li><a href="#">About</a></li>
  <li><a href="#">Division</a></li>
  <li><a href="#">Career</a></li>
  <li><a href="#">MChoice's</a></li>
</ul>

Answer №4

If you want to change the color of the active link in your navigation, you can follow these steps:

  1. When a navigation link is clicked, apply a CSS class:
$('ul li a').click(function(){
    $('li a').removeClass("active");
    $(this).addClass("active");
});
  1. Define CSS styles for the active class:
ul li a.active {
    background-color: #f4f4f4;
}

Answer №5

To add a highlight effect to your active element in CSS, you can utilize the active selector. This selector will change the background color of the element when it is clicked.

a:active { 
    background-color: yellow;
}

a:focus { 
    background-color: yellow;
}

If you want to toggle this effect on and off using JQuery, you can check out a helpful post on Stack Overflow that provides a solution.

(Related to How to keep :active css style after clicking an element)

jQuery('button').click(function(){
   jQuery(this).toggleClass('active');
});

Answer №6

function changeButtonColor() {

  $(".inclusive-buttons").on("click", "a", function() {
    $(".inclusive-buttons a").css("background", "#333");
    $(this).css("background", "red");
  })
  
}

var x = document.getElementsByTagName("li");
x.onclick = changeButtonColor();
body {
  margin: 0;
}

.logo {
  margin: 0;
  padding: 0;
  overflow: hidden;
  background-color: #f2f2f2;
  float: left;
  width: 25%;
}

ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
  overflow: hidden;
  background-color: #333;
}

li {
  float: left;
}

li a {
  display: block;
  color: white;
  text-align: center;
  padding: 14px 40px;
  text-decoration: none;
  font-size: 18px;
}

li a:hover {
  background-color: #111;
}
a:active { 
    background-color: red;
}
<script
  src="https://code.jquery.com/jquery-3.2.1.min.js"
  integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
  crossorigin="anonymous"></script>

<ul class="inclusive-buttons">
  <li><a href="#">Home</a></li>
  <li><a href="#">News</a></li>
  <li><a href="#">Contact</a></li>
  <li><a href="#">About</a></li>
  <li><a href="#">Division</a></li>
  <li><a href="#">Career</a></li>
  <li><a href="#">MChoice's</a></li>
</ul>

https://jsfiddle.net/m5gm7x7e/2/

Answer №7

HTML Section

 <div class="menu">
    <div class="menu-fixed" style="position: fixed;">
       <div class="container" style="width: 100%;">
          <div class="menu-collapse" id="menu-collapse">
             <ul class="menu-list" id="menu-list">
                 <li id="Home"><a href="#Home">Home</a></li>
                 <li id="Services"><a href="#Services">Services</a></li>
                 <li id="Portfolio"><a href="#Portfolio">Portfolio</a></li>
                 <li id="Testimonials"><a href="#Testimonials">Testimonials</a></li>
                 <li id="Team"><a href="#Team">Team</a></li>
                 <li id="ContactUs"><a href="#ContactUs">Contact Us</a></li>
                 <li id="Blog"><a href="#Blog">Blog</a></li>
                 <li id="Shop"><a href="#Shop">Shop</a></li>                     
             </ul>
          </div>
       </div>
    </div>
 </div>

JavaScript Section

$(function() {
        $('#menu-list li a').click(function() {
           $('#menu-list li').removeClass();
           $($(this).attr('href')).addClass('active');
        });
     });

CSS Section

.menu #menu-list > .active > a {
    color: blue;
}

Check out the JSFiddle demonstration

http://jsfiddle.net/Ag47D/775/

Answer №8

Take a look at this JSFiddle: https://jsfiddle.net/timhjellum/nw3n7eka/103/

This jQuery solution checks the page URL (window.location) for a specific string defined in the .indexOf(" add a unique string here "). If the string is found, it adds the class "active" to the corresponding li element with the assigned class.

In this example, I'm using "display" as the string to match in the URL, due to the URL structure of the JSFiddle iframe.

Navigation structure:

$(document).ready(function () {
     if(window.location.href.indexOf("home") > -1) {
         $(".home").addClass("active");
     }
     if(window.location.href.indexOf("display") > -1) {
         $(".news").addClass("active");
     }
     //repeat for each navigation element
});

To implement this, modify the HTML as follows:

<ul>
  <li class="home"><a href="index">Home</a></li>
  <li class="news"><a href="display">News</a></li>
  <li class="contact"><a href="contact">Contact</a></li>
  <li class="about"><a href="about">About</a></li>
</ul>

Add the following CSS:

li.active {
  background-color: white;
}
li.active a {
  color: black;
}

If jQuery is not an option for you, let me know. This solution is easy to implement and customize.

Answer №9

If you want to create a more personalized look for each page on your website, consider using separate classes within your CSS file. For example, you could define classes like "ul-home" and "ul-news" with different background colors. Then, simply assign the appropriate class to the <ul> tag on each page:

.ul-home {
    background-color: blue;
}
.ul-news {
    background-color: green;
}

On the home page:

<ul class="ul-home">
    <li>Home</li>
    <li>News</li>
</ul>

On the news page:

<ul class="ul-news">
    <li>Home</li>
    <li>News</li>
</ul>

Repeat this process for each page to create a customized experience for your visitors.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to include a validation process for Login Details in case of errors

Is it possible to implement Login Details confirmation for incorrect entries? My desired outcome is that when a user enters their credentials and the userID and Password are correct, but the user type is wrong, upon clicking the login button it should di ...

Tips for Positioning a Page Layout in the Center Using HTML and CSS

I'm a beginner in HTML and CSS and I'm trying to create a simple webpage layout from scratch. I want all the elements of the page (nav, header, section, footer, etc.) to be centered while still keeping the nav bar on the left side. I've set ...

The carousel's slides don't behave properly when swiping or using the slider controls (next/prev)

I have recently completed the construction of a carousel with swipe/touch functionality and control buttons for previous and next slides. However, I am facing an issue with the behavior of the carousel as it seems to be sliding by 2 or 3 instead of one at ...

Values do not appear as expected post PDF conversion using wkhtmltopdf

Currently, I am updating certain values within my HTML page by following this process: The function: function modifyContent(){ var newTitle = document.getElementById('myTextField1').value; if( newTitle.length==0 ){ alert('Plea ...

Show a few values as a string in Angular using Typescript

I am working with JSON data and I want to know how to display hobbies without including the word "all" in an Angular/TypeScript application. { "Name": "Mustermann1", "Vorname": "Max1", "maennlich& ...

Populating dropdown menu with data fetched from an AJAX request

I've created a dropdown in my cshtml page: @( Html.Kendo().DropDownList().Name("ddlCode").OptionLabel("Select Code...").BindTo(@ViewBag.dropDown) .DataTextField("Title") .DataValueField("domainCode") The dropdown is bound up ...

Exploring JSON data in JavaScript

In my Json data, I have a nested structure of folders and files. My goal is to determine the number of files in a specific folder and its sub-folders based on the folder's ID. Below is an example of the JSON dataset: var jsonStr = { "hierarchy": ...

Clearing a textarea in jQuery that is populated with text

Having an interesting dilemma. I'm trying to clear a <textarea> and then replace it with new content. The functions in the JSFiddle will work perfectly fine if the textarea is left empty, but as soon as any text is manually typed into it, the me ...

What are the steps to integrate mp3 music into my web application?

Does anyone have experience implementing auto-resume mp3 music on a web application so that the music continues to play even when the user changes pages? I would like the music to seamlessly play as the user navigates through my web application. Can someo ...

The page you are looking for cannot be located using Jquery AJAX JSON PHP POST -

Whenever I attempt to POST some JSON data to a local host, I consistently encounter a 404 Not Found error. Strangely enough, the php file is positioned precisely where it should be according to the script instructions. If anyone has dealt with this issue b ...

Issue with Express.js: "opencv" module not found within a Docker container

Currently, I am in the process of setting up the OpenCV bindings for NODE to enable AI functionality on my express server. For this purpose, I am utilizing the Peter Braden Library - https://github.com/peterbraden/node-opencv. However, I am encountering a ...

Change the position of a Div by clicking on a different Div using JQuery for custom movements

I have successfully managed to slide the div left/right based on the answers below, but I am encountering some issues with the top div. Here are the specific changes I am looking to make: 1. Make both brown lines thinner without affecting the animations. ...

The Redux state is not being refreshed

I've been attempting to update the redux store by fetching a list of group names using axios within the action. Despite receiving a response from the API call, the redux store fails to reflect the updated data. FileName: actions/index.js CODE: expo ...

Modify the HTML within my web browser view

Is there a way for me to dynamically change the .html content in my webView based on what is currently displayed? I am looking to implement functionality similar to that of a modalViewController but for manipulating .html files. Any suggestions or method ...

`To activate/deactivate tabs by choosing options from drop-down menus`

Hey there, I'm currently dealing with a combo box that has 5 drop down items in Tab1. There are also other tabs present such as tab2, tab3, tab4, and tab5. Tab1 is enabled while the other tabs are disabled. Each of the disabled tabs contains different ...

The MUI Time picker fails to display the correct time value in the input field with proper formatting

My primary goal is to implement a MUI time picker with yup validation and react-hook-form. However, I am encountering an issue where the selected time from the time picker is not being updated in the text field as expected. https://i.sstatic.net/LVkgK.png ...

Encountered an error while trying to download a PDF document in React

I'm currently working on adding a button to my website portfolio that allows users to download my CV when clicked. The functionality works perfectly fine on my localhost, but after deploying it to AWS Amplify, I encountered an error. The error occurs ...

Encountered an Xpath error while attempting to create a random email generator using Selenium IDE

While attempting to execute a script, I encountered an "element not found" error with Selenium failing to detect the xpath. My goal is to randomly generate email addresses. Every time there is an error message stating: [error] Element .//[@id='GmailA ...

Challenges with Scope in Using AJAX Calls within an Infowindow

Could it be a scope issue? Feel free to correct me if I'm mistaken. I've got a for loop that's placing markers on my map. Each marker has a different infowindow that loads content using ajax callbacks. This is a simplified version of the s ...

The minmax() function in a responsive grid layout does not function properly when incorporating grid areas

My Vision for the Layout I am striving to create a dynamic grid structure with three columns and two rows, where the third column spans both rows and features an image. This layout should adjust itself based on the device screen size: Specifically, I wou ...