Tips for updating the color of the active menu item on a website in real-time

As someone who is new to web development, I am interested in creating menus similar to the ones found on stackoverflow.com (such as Questions, Tags, and Users shown above). My main question is how can I change the color of a selected menu item? For example, when a user clicks on the 'Questions' menu, I want the background color to change to orange.

I have been able to change the color while hovering using CSS, which was easy enough. However, I am struggling to figure out how to achieve this effect for clicked items.

Is it possible to change the color of a clicked item using only CSS?

Answer №1

Define the styles for both active and hover states:


To activate the li element on the server side, you must determine which page is currently loaded while generating the menu:

 <li class="active">Question</li>
 <li>Tags</li>
 <li>Users</li>

If content is being changed dynamically without a reload, setting the active li element on the server becomes impractical and JavaScript must be used:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
<style>
  .menu{width: 300px; height: 25; font-size: 18px;}
  .menu li{list-style: none; float: left; margin-right: 4px; padding: 5px;}
  .menu li:hover, .menu li.active {
        background-color: #f90;
    }
</style>
</head>
<body>

<ul class="menu">
<li>Item 1</li>
<li class="active">Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
<li>Item 5</li>
<li>Item 6</li>
</ul>

<script type="text/javascript">

var make_button_active = function()
{
  //Get item siblings
  var siblings =($(this).siblings());

  //Remove active class on all buttons
  siblings.each(function (index)
    {
      $(this).removeClass('active');
    }
  )


  //Add the clicked button class
  $(this).addClass('active');
}

//Attach events to menu
$(document).ready(
  function()
  {
    $(".menu li").click(make_button_active);
  }  
)

</script>
</body>

</html>

Answer №2

To make the implementation smoother, considering the utilization of JavaScript would be beneficial ... Below is a demonstration using JQuery script ... As previously pointed out by others ... we are utilizing a class called 'active' to signify the active tab - NOT the pseudo-class ':active.' Nevertheless, it could have been named anything else such as selected, current, and so forth.

/* Styling with CSS */

#nav { width:480px;margin:1em auto;}

#nav ul {margin:1em auto; padding:0; font:1em "Arial Black",sans-serif; }

#nav ul li{display:inline;} 

#nav ul li a{text-decoration:none; margin:0; padding:.25em 25px; background:#666; color:#ffffff;} 

#nav ul li a:hover{background:#ff9900; color:#ffffff;} 

#nav ul li a.active {background:#ff9900; color:#ffffff;} 

/* Example Using JQuery */

<script type="text/javascript">
$(function (){

    $('#nav ul li a').each(function(){
        var path = window.location.href;
        var current = path.substring(path.lastIndexOf('/')+1);
        var url = $(this).attr('href');

        if(url == current){
            $(this).addClass('active');
        };
    });         
});

</script>

 /* HTML Structure */

<div id="nav" >
    <ul>
        <li><a href='index.php?1'>One</a></li>
        <li><a href='index.php?2'>Two</a></li>
        <li><a href='index.php?3'>Three</a></li>
        <li><a href='index.php?4'>Four</a></li>
    </ul>
</div>

Answer №3

Apologies for the delayed response, but tackling this question is actually quite simple. All you need to do is designate multiple tab classes in your CSS file, and then specify the required tab as your class in the PHP file when creating the LI tag.

Let me demonstrate how you can achieve this solely on the server side:

CSS

html ul.tabs li.activeTab1, html ul.tabs li.activeTab1 a:hover, html ul.tabs li.activeTab1 a  { 
    background: #0076B5;
    color: white;
    border-bottom: 1px solid #0076B5;
}

html ul.tabs li.activeTab2, html ul.tabs li.activeTab2 a:hover, html ul.tabs li.activeTab2 a {
    background: #008C5D;
    color: white;
    border-bottom: 1px solid #008C5D;
}

PHP

<ul class="tabs">
    <li <?php print 'class="activeTab1"' ?>>
        <a href="<?php print 'Tab1.php';?>">Tab 1</a>
    </li>

    <li <?php print 'class="activeTab2"' ?>>
        <a href="<?php print 'Tab2.php';?>">Tab 2</a>
    </li>
</ul>

Answer №4

If you're looking to update the color of the currently highlighted link/tab, the most effective approach is to assign a class (such as active) to the active link/tab and customize its styling.

For instance, your CSS could look like:

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

Answer №5

My approach involves utilizing PHP to identify the URL and match the page name (excluding the .php extension). By adding a common word like "contact" to multiple pages, each with the same class, I can easily add additional CSS properties using PHP.

To implement this method, it is necessary to save your pages with the file extension .php.

Below is a demonstration. Customize the links and pages according to your requirements. The CSS class assigned to all links is .tab, with an additional class called .currentpage for the active link (following the PHP function), providing a space to override your CSS styles. Feel free to assign any names you prefer.

<?php # Utilizing REQUEST_URI
    $currentpage = $_SERVER['REQUEST_URI']; ?>
<div class="nav">
    <div class="tab
         <?php
             if(preg_match("/index/i", $currentpage)||($currentpage=="/"))
                 echo " currentpage";
         ?>"><a href="index.php">Home</a>
     </div>
     <div class="tab
         <?php
             if(preg_match("/services/i", $currentpage))
                 echo " currentpage";
         ?>"><a href="services.php">Services</a>
     </div>
     <div class="tab
         <?php
             if(preg_match("/about/i", $currentpage))
                 echo " currentpage";
         ?>"><a href="about.php">About</a>
     </div>
     <div class="tab
         <?php
             if(preg_match("/contact/i", $currentpage))
                 echo " currentpage";
         ?>"><a href="contact.php">Contact</a>
     </div>
 </div> <!--nav-->

Answer №6

Give this a try. This code will maintain the color of an item until another one is selected.

<style type="text/css>

.activeElem{
 background-color:lightblue
}       
.desactiveElem{
 background-color:none
}       

}

</style>

<script type="text/javascript>
var activeElemId;
function activateItem(elemId) {
 document.getElementById(elemId).className="activeElem";
 if(null!=activeElemId) {
   document.getElementById(activeElemId).className="desactiveElem";
 }
 activeElemId=elemId;

}
</script>

<li id="aaa"><a href="#" onclick="javascript:activateItem('aaa');">AAA</a>
<li id="bbb"><a href="#" onClick="javascript:activateItem('bbb');">BBB</a>
<li id="ccc"><a href="#" onClick="javascript:activateItem('ccc');">CCC</a>

Answer №7

If you're looking for a simple CSS solution, I have one that I currently use.

Start by assigning a unique ID or class to your webpage and menu items, then implement the following code:

HTML:

<html>
    <body id="unique_id_here">
        <ul class="menu">
            <li id="menu_item1">Item 1</li>
            <li id="menu_item2">Item 2</li>
            <li id="menu_item3">Item 3</li>
        </ul>
        ...
    </body>
</html>

CSS:

.menu li:hover,
#unique_id_here #menu_item1,
#unique_id_here #menu_item2,
#unique_id_here #menu_item3 {
    background-color: #f90;
}

Answer №8

Finally, with the assistance of everyone and a helpful post titled How to change link style onclick, I was able to achieve my goal. Below is the JavaScript code I used to accomplish this task.

<html>
    <head>
        <style type="text/css">
            .item {
                width:900px;
                padding:0;
                margin:0;
                list-style-type:none;
            }

            a {
                display:block;
                width:60;
                line-height:25px; /*24px*/
                border-bottom:1px  none #808080;
                font-family:'arial narrow',sans-serif;
                color:#00F;
                text-align:center;
                text-decoration:none;
                background:#CCC;
                border-radius: 5px;
                -webkit-border-radius: 5px;
                -moz-border-radius: 5px;
                margin-bottom:0em;
                padding: 0px;
            }

            a.item {
                float:left;        /* For horizontal left to right display. */
                width:145px;       /* For maintaining equal  */
                margin-right: 5px; /* space between two boxes. */
            }

            a.selected{
                background:orange;
                color:white;
            }
        </style>
    </head>
    <body>
        <a class="item" href="#" >item 1</a>
        <a class="item" href="#" >item 2</a>
        <a class="item" href="#" >item 3</a>
        <a class="item" href="#" >item 4</a>
        <a class="item" href="#" >item 5</a>
        <a class="item" href="#" >item 6</a>

        <script>
            var anchorArr=document.getElementsByTagName("a");
            var prevA="";
            for(var i=0;i<anchorArr.length;i++)
            {
                anchorArr[i].onclick = function(){
                    if(prevA!="" && prevA!=this)
                    {
                        prevA.className="item";
                    }
                    this.className="item selected";
                    prevA=this;
                }
            }
        </script>
    </body>
</html>

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

Using the swiper carousel on WordPress results in an unexpected horizontal scrolling issue

Running an Elementor website, I need to incorporate various image carousels within my post content. Initially, I created a template for each carousel using Elementor. However, I have now decided to switch to utilizing a shortcode that leverages Elementor&a ...

How can we target every nth child element universally?

I am working with an HTML structure that has a specific layout, and I need to target all odd <span> elements globally without considering their parent elements. Is there a way to style 1, 3, 5, 7, 9 in red color? I attempted to use :nth-child(odd) b ...

Sticky positioning and visible overflow restrictions

When position sticky is used within a container with overflow:hidden, it does not work as expected. However, the overflow hidden property is necessary in this case. <div class="lg:col-start-7 lg:col-end-13" style="overflow:hidden"&g ...

What strategies can I use to enhance the efficiency of my code using AngularJS?

After conducting extensive research, I am still unable to find a solution or comprehend the code written by someone else - it simply does not work. As a result, my codebase has grown significantly. I am interested in optimizing my code using AngularJS func ...

Creating an array using Vue.js

When I initialize a Vue data array like this [0: Object, 2: Object];, the console log in Vue shows the array as [0: Object, 1: undefined 2: Object];. This causes issues when iterating through with 'v-for="cell in row.cells"' as it results in tryi ...

Utilizing a foreach loop to control the behavior of two distinct radio buttons as a unified

Can someone help me with a code containing a 5 star rating system (radio button) for two different questions? The issue is that the ratings for each question are linked, so when I make a selection in one question, it clears the selection in the other. It& ...

Upload several files sequentially in a form on a website using Selenium with Python

I need to automate the process of inputting multiple files from a folder into a website and running an online job for each file. Currently, I can only input one file at a time using this code snippet. from selenium import webdriver url = "http://www.exam ...

Arranging individual spans within a div using CSS for perfect alignment

My current code looks like this: <div id='div_selectores' class='row_titulo '> <span class="label_selector" id="lbl_show"></span><span id="div_selector_show"></span> <br /> <span class ...

Changing the color of a div while implementing a show and hide effect in JavaScript

I have designed a checkout system with three distinct parts - shipping information, billing information, and order confirmation. These sections are all on the same page, allowing for a seamless flow during the checkout process. Once a customer completes t ...

Tips for activating an HTML input field using Javascript

I am currently using localStorage to store a string input by the user as a title, which will be saved for future visits. I would like to implement a button that allows the user to delete the displayed text (from localstorage) and enables the input field fo ...

Modifying the Position of the Search Box within DataTables by Manipulating DOM Elements

As a newcomer to the jQuery datatables plugin, I am still learning how to use it effectively. I have connected the plugin to my tables using the following code: $(document).ready(function() $('#table_id').dataTable({ }); }); ...

Is it possible to execute the Go compiler within a web browser?

Just discovered that Go can be compiled to WebAssembly. How awesome! According to this Go documentation, the Go toolchain is actually written in Go itself. This got me thinking, is it possible to run the Go compiler in a browser? Can I create a website w ...

Incorporating an image within a table while maintaining 100% height: A step-by-step guide

I'm struggling to make the image fit 100% to the height of a CSS-created table. The table and image seem to be ignoring the dimensions of the parent element, as shown below. Since everything needs to be dynamic, I am working with percentages. .img ...

"Click-to-Submit Button Triggering Error Notification before Redirecting to New Page

I am looking to implement an error message for a button and then redirect the user to a specific URL. However, I am unsure of how to achieve this using JQuery as I am relatively new to it. The idea is that the user uploads a file and then clicks on the Sub ...

Browser switch dependent on operating system

Recently, a guest raised concerns about a DIV element covering the content of the page. There is an issue with a popup that is supposed to only appear when the mouse hovers over its container: <td class="ref" id="myContainer"> <div><a ...

What is the best way to display value in a dropdown option field using Laravel?

I am currently working with 3 tables: hosts, visitors, and visitor_types. My objective is to display the host name and visitor type in a drop-down option button. However, I find myself a bit perplexed when it comes to the controller and route code. I have ...

What is the best way to apply a semi-transparent background to my navigation bar, while maintaining a blue background across my entire page?

Currently, I have a background set for my website along with a navigation bar that displays my name and additional information. I am looking to make the background of this navigation bar semi-transparent so that it is possible to see through it. I tried ...

Delete the right border on the items in the bottom row

I have a list of items with three rows. I want to separate the first and second row with borders, so I added a right border to those items but excluded the third row from having borders. .test-row { display: grid; grid-template-rows: 1fr 1fr 1fr; ...

After adding more rows, the css formatting seems to disappear

After populating flexigrid using a JavaScript method from another .js file, I noticed that the CSS is lost once new rows are inserted. Surprisingly, other sections on the page are not affected. The code snippet I am using is as follows: var newTbl = &apo ...

Turn off automatic downloading of embedded frame content in Safari for iOS

I am encountering an issue with a modal that displays a PDF and offers two options - one to print and one to download. The download option uses a blob with content-type: application/octet-stream, while the print option utilizes a blob with content-type: a ...