Dynamic Menu Highlight Styling

I'm having trouble highlighting the current menu item when clicked using CSS. Here is the code I have:

#sub-header ul li:hover{ background-color: #000;}
#sub-header ul li:hover a{ color: #fff; }
#sub-header ul li.active{ background-color: #000; }
#sub-header ul li.active a{ color: #fff; }

And here is the corresponding HTML:

<div id="sub-header">
    <ul>
        <li> <a href="index.php">Home</a> </li>
        <li> <a href="contact.php">Contact Us</a> </li>
        <li> <a href="about.php">About Us</a> </li>
    </ul>
</div>

I am able to highlight the menu item on hover, but it does not remain highlighted after clicking.


@Jonathan, thanks for your suggestion, but I found a simpler solution that worked for me:

Here's my updated JavaScript:

$(function(){
    var url = window.location.href; 

    $("#sub-header a").each(function() {
        if(url == (this.href)) { 
            $(this).closest("li").addClass("active");
        }
    });
});

And in my CSS file:

.active { background-color: #000; }
/* Overrides existing styles for "a" tags */
#sub-header .active a{ color: #fff; }

Answer №1

Make sure to add specific classes to the body of each page:

<body class="home">

If you're currently on the contact page, use this:

<body class="contact">

Keep these class names in mind when designing your CSS styles:

#sub-header ul li:hover,
body.home li.home,
body.contact li.contact { background-color: #000;}

#sub-header ul li:hover a,
body.home li.home a,
body.contact li.contact a { color: #fff; }

Remember to assign class names to your list items as well:

<ul>
  <li class="home"><a href="index.php">Home</a></li>
  <li class="contact"><a href="contact.php">Contact Us</a></li>
  <li class="about"><a href="about.php">About Us</a></li>
</ul>

By doing this, when you're on the body.home page, the styling for li.home a will indicate that it is the current page.

Answer №3

add a simple method

<div id='cssmenu'>
<ul>
<li class=''><a href='1.html'><span>1</span></a></li>
<li class=''><a href='2.html'><span>2</span></a></li>
<li class='' style="float:right;"><a href='3.html'><span>3</span></a></li>
</ul>
</div>

$("document").ready(function(){
$(function() {
$('.cssmenu a[href="' + location.pathname.split("/")[location.pathname.split("/").length-1] + '"]').parent().addClass('active');
});

});

Answer №4

Since the tag assigned to this question is CSS, I will share how I achieved it.

  1. Start by creating a class in your .css file:

    a.activePage{ color: green; border-bottom: solid; border-width: 3px;}

  2. Your navigation bar structure should look like this:

    • Home
    • Contact Us
    • About Us

NOTE: If you are already styling all of your nav-bar elements with a general class, you can add the specific-class we created to overwrite those styles by placing it after the common class in the html-tag.

For example: If you have a class named 'navList' for all list items and want to apply special-case styling from class 'activePage'.

.CSS file:

a.navList{text-decoration: none; color: gray;}
a.activePage{ color: green; border-bottom: solid; border-width: 3px;}

.HTML file:

<div id="sub-header">
    <ul>
        <li> <a href="index.php" class= "navList activePage" >Home</a> </li>
        <li> <a href="contact.php" class= "navList">Contact Us</a> </li>
        <li> <a href="about.php" class= "navList">About Us</a> </li>
    </ul>
</div>

See how one class name follows another for cascading effect.

Answer №5

Perhaps this might not be the most efficient method, but I'm going to share it anyway.

I utilized PHP, Bootstrap, and Font Awesome in creating my solution.

Basically, I have two pages: 1. index and 2. create-user

Add the following code snippet above your existing code:

<?php
$name=basename($_SERVER["REQUEST_URI"]);
$name=str_replace(".php","",$name);
switch ($name) {
    case "create-user":
        $a = 2;
        break;
    case "index":
        $a = 1;
        break;
    default:
        $a=1;
}
?>

For the menu functionality, add

<?php if($a==1){echo "active";} ?>
in the class attribute for menu item 1, and for menu item 2, add
<?php if($a==2){echo "active";} ?>

<ul id="menu" class="navbar-nav  flex-column text-right mt-3 p-1">
                        <li class="nav-item mb-2">
                            <a href="index.php" class="nav-link text-white customlihamid <?php if($a==1){echo "active";} ?>"><i
                                        class="fas fa-home fa-lg text-light ml-3"></i>dashboard</a>
                        </li>
                        <li class="nav-item mb-2">
                            <a href="#" href="javascript:" data-parent="#menu" data-toggle="collapse"
                               class="accordion-toggle nav-link text-white customlihamid <?php if($a==2){echo "active";} ?>" data-target="#tickets">
                                <i class="fas fa-user fa-lg text-light ml-3"></i>manage users
                                <span class="float-left"><i class="fas fa-angle-down"></i></span>
                            </a>

                            <ul class="collapse list-unstyled mt-2 mr-1 pr-2" id="tickets">
                                <li class="nav-item mb-2">
                                    <a href="create-user.php" class="nav-link text-white customlihamid"><i class="fas fa-user-plus fa-lg text-light ml-3"></i>add user</a>
                                </li>

                                <li class="nav-item mb-2">
                                    <a href="#" class="nav-link text-white customlihamid"><i class="fas fa-user-times fa-lg text-light ml-3"></i>delete user</a>
                                </li>

                            </ul>
                        </li>

                    </ul>

Also, remember to include the following CSS styles:

.customlihamid {
    transition: all .4s;
}

.customlihamid:hover {
    background-color: #8a8a8a;
    border-radius: 5px;
    color: #00cc99;
}
.nav-item > .nav-link.active  {
    background-color: #00cc99;
    border-radius: 7px;
    box-shadow: 5px 7px 10px #111;
    transition: all .3s;
}
.nav-item > .nav-link.active:hover  {
    background-color: #8eccc1;
    border-radius: 7px;
    box-shadow: 5px 7px 20px #111;
    transform: translateY(-1px);
}

Lastly, don't forget to implement the JavaScript functionality:

$(document).ready(function () {
   $('.navbar-nav .nav-link').click(function(){
      $('.navbar-nav .nav-link').removeClass('active');
      $(this).addClass('active');
   })
});

Before adding the JavaScript code, make sure to test your work without it to understand its purpose.

Answer №6

Imagine we're working with a menu structure like this:

<div class="menu">
  <a href="link1.html">Link 1</a>
  <a href="link2.html">Link 2</a>
  <a href="link3.html">Link 3</a>
  <a href="link4.html">Link 4</a>
</div>

Let's assume our current URL is https://demosite.com/link1.html

The function below can be used to dynamically add an "active" class to the link in the menu that corresponds to our current URL:

let currentURL = window.location.href;

document.querySelectorAll(".menu a").forEach(item => {
  if(currentURL.indexOf(item.getAttribute("href")) !== -1){
    item.classList.add("active");
  }
})

Answer №7

To start, assign unique identifiers to all your links and create a CSS class named active:

<ul>
    <li><a id="link1" href="#/...">link 1</a></li>
    <li><a id="link2" href="#/...">link 2</a></li>
</ul>

CSS:

.active {
    font-weight: bold;
}

Using Jquery:

function setActiveLink(setActive){
    if ($("a").hasClass('active'))
        $("a").removeClass('active');
    if (setActive)
        $("#"+setActive).addClass('active');
}

$(function() {
    $("a").click(function() {
        setActiveLink(this.id);
    });
});

Using Vanilla JavaScript:

To avoid selecting excess links with document.querySelectorAll, assign an id of menuLinks to the parent element. Include an onClick handler on the links.

<ul id="menuLinks">
    <li><a id="link1" href="#/..." onClick="setActiveLink(this.id);">link 1</a></li>
    <li><a id="link2" href="#/..." onClick="setActiveLink(this.id);">link 2</a></li>
</ul>

JavaScript Code:

function setActiveLink(setActive){
    var links = document.querySelectorAll("#menuLinks a");
    Array.prototype.map.call(links, function(e) {
        e.className = "";
        if (e.id == setActive)
            e.className = "active";
    })
}

Answer №8

It's important to reference the current element rather than all elements that match your selector.

$("#mainMenu td").click(function() {
$(this).css('background-color', '#EDEDED');

});

Consider using CSS classes instead of directly setting CSS properties.

For example, you can do this:

$("#mainMenu td").click(function() {
$(this).addClass('selected');

});

And add the following CSS:

#mainMenu td.selected {

background-color: #EDEDED; }

Answer №9

Give this a try (Make sure to copy and paste):

Sample.html:-

<html>
 <link rel="stylesheet" type="text/css" href="custom-style.css">
 <a class="food" href="#">Home</a></span>
 <a class="food"  href="#">About</a></span>
 <a class="food"  href="#">Contact</a></span>
</html>

custom-style.css:-

a:link{
 color:blue;
}

a:visited{
 color:purple;
}

a:hover{
 color:orange;
}
a:focus{
color:green;
}

a:active{
 color:red;
}

a:active{
 color:yellow;
}

Answer №10

Here is another approach using a simple 2-line listener

$( ".menu_button" ).click(function() {

    $( ".menu_button" ).removeClass('menu_button_highlight');
    $(this).addClass('menu_button_highlight');
});

=====

    <a class='menu_button' href='#admin'>Admin</a>
    <br/>

    <a class='menu_button' href='#user_manager'>User Manager</a>
    <br/>

    <a class='menu_button' href='#invite_codes'>Invite Codes</a>

====

.menu_button {

    padding: 0 5px;
}

.menu_button_highlight {

    background: #ffe94c;
}

Answer №11

After reading @Sampson's solution, I decided to tackle the problem in the following manner -

HTML:

  1. Each page contains a div with a class of content, holding the specific content for that page while keeping header and footer separate.
  2. To differentiate each page, I assigned a unique class within the content div. For example, for a 'CONTACT US' page, the structure would be:
    <section class="content contact-us"></section>
    .
  3. This setup allows me to write targeted CSS for individual pages within a single style.css file.

<body>
    <header>
        <div class="nav-menu">
            <ul class="parent-nav">
                <li><a href="#">Home</a></li>
                <li><a href="#">Contact us</a></li>
                ...
            </ul>
        </div>
    </header>

    <section class="content contact-us">
        Content for contact us page goes here
    </section>

    <footer> ... </footer>

</body>

CSS:

  1. I created a universal active class containing styling for active menu items.

.active {
    color: red;
    text-decoration: none;
}
<body>
    <header>
        <div class="nav-menu">
            <ul class="parent-nav">
                <li><a href="#">Home</a></li>
                <li><a href="#">Contact us</a></li>
                ...
            </ul>
        </div>
    </header>

    <section class="content contact-us">
        Content for contact us page goes here
    </section>

    <footer> ... </footer>

</body>

JavaScript:

  1. In JavaScript, I compare the menu link text with the unique class name defined in HTML using jQuery.
  2. Firstly, I format all menu texts to lowercase and replace spaces with hyphens to match the class name.
  3. If the content class matches the menu text (lowercase without spaces), the active class is applied to the menu item.

var $allMenu = $('.nav-menu > .parent-nav > li > a');
var $currentContent = $('.content');
$allMenu.each(function() {
  $singleMenuTitle = $(this).text().replace(/\s+/g, '-').toLowerCase();
  if ($currentContent.hasClass($singleMenuTitle)) {
    $(this).addClass('active');
  }
});
.active {
  color: red;
  text-decoration: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>;

<body>
  <header>
    <div class="nav-menu">
      <ul class="parent-nav">
        <li><a href="#">Home</a></li>
        <li><a href="#">Contact us</a></li>
        ...
      </ul>
    </div>
  </header>

  <section class="content contact-us">
    Content for contact us page goes here
  </section>

  <footer> ... </footer>

</body>

Reasoning Behind This Approach:

  1. @Sampson's method was effective, but I found myself consistently adding new code for each page. My approach streamlines this process.
  2. In my project, the body tag resides in the header.php file, preventing unique class names on a per-page basis.

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

Warning thrown when Ajax call is executed within a function, causing it to break

I'm in the process of refactoring a JavaScript file that performs multiple ajax calls. I have a function that makes an ajax call, retrieves an object with details required for other ajax calls. const makeCall = (url, type, data, done) => { $.aj ...

Checking for radio button selection with JQuery on page load

Is it possible to use jQuery to automatically select a specific radio button upon the page loading? I am looking for a way to set a particular radio button item as checked using jQuery when the page is initially loaded. Can this be achieved with jQuery?r ...

Issue with div in simple HTML code

I've been facing challenges with this line of HTML as I keep encountering errors and cannot pinpoint the source. The error highlight appears at the end of the last div, but once removed, another error emerges at the end of the body tag. Check out the ...

React Color Input: The input format should follow the pattern of "#rrggbb", with rr, gg, and bb being two-digit hexadecimal values

The code is functioning correctly and as expected. The background color of the squares changes when each input is modified, and the squares update once the button is pressed. During development, there was a moment when the warning mentioned appeared brief ...

Understanding the significance of underscores in JavaScript strings

Some places mention using _() around strings like _('some string'). For instance, in a desktop program with these imports: const Applet = imports.ui.applet; const St = imports.gi.St; const Gdk = imports.gi.Gdk; const Gtk = imports.gi.Gtk; const ...

Tips on achieving vertical movement within a div element from the bottom of the wrapper to the

I am struggling to animate a .alert div within its wrapper to fly up from the bottom of the wrapper by 40px. However, I am encountering difficulty as the alert div does not start at the bottom of the wrapper as intended. The desired behavior is for it to s ...

Using AngularJS routing with an Express 4.0 backend API

Recently, I began working on an application utilizing Express 4.0 server. Following a tutorial on scotch.io (http://scotch.io/tutorials/javascript/build-a-restful-api-using-node-and-express-4), I structured the routes to support a backend api serving an An ...

Tips for retrieving multiple values or an array from an AJAX request?

Is there a correct way to pass multiple sets (strings) of data back after executing an ajax call in php? I understand that echo is typically used to send a single string of data back, but what if I need to send multiple strings? And how should I handle th ...

Using JavaScript to develop a demonstration of the capabilities of Microsoft's Cognitive

Having trouble getting this basic example of the Microsoft Cognitive Services to work in JavaScript. Need some help or a working example, please! I've attempted to run the code in both node and browser with necessary modifications. Encountering an e ...

Is it possible for a nested div to override the hover effect of its parent?

Is it possible for a nested div to override the hover effects of its parent? Here's an example: .Box { width: 50px; height: 50px; background: red; } .Circle { width: 20px; height: 20px; background: blue; border-radius: 20px; } .Bo ...

NodeJs error: the response status function is missing

Encountering the error message "res.status is not a function" while working with this route. Any suggestions on how to resolve this issue? Thank you! exerciseRouter.post('/update/:id', (res, req) => { Exercise.findById(req.id) .th ...

Image gradually disappears after being loaded via ajax request

I am trying to achieve a fade-in effect for images after they have been loaded following an ajax call. The goal is to make the fade-in occur smoothly, rather than having the user observe the image loading process. Is there anyone who can assist me with ...

Communicating PHP variables with JavaScript through AJAX in a chat application

Hello there! I am currently in the process of developing a chat application for my website that includes user registration and login. My backend server is built using NodeJS to leverage SocketIO capabilities. Within my index.php file, I have implemented ...

Problem with special characters in Localstorage for Internet Explorer 8

After developing a jQuery script that retrieves data from a service, stores it in local storage, and displays it on the page upon a specific event, I encountered an issue with displaying Chinese characters only on IE8+ browser. Unfortunately, IE is unabl ...

What could be causing the JSON output to appear in a disordered fashion?

I am attempting to retrieve weather information for 8 different locations. Utilizing a weather API that requires longitude and latitude, it returns JSON output with the weather data for each location. I provided the coordinates in sequential order from 0 t ...

Outer div encapsulating inner div within its boundaries

I am looking for a solution where the inner div stays fully contained within the outer div, without overflowing and overlapping with the padding of the outer div. Here is a code sample that demonstrates the issue .inner { /* Overflow */ overflow-wra ...

What is preventing my HTML from rendering on the page?

I have cross-referenced the script below with the google charts documentation available at the following link: https://developers.google.com/chart/interactive/docs/gallery/scatterchart However, it is not displaying properly. I have reviewed the code and ...

Card Alignment with Bootstrap

I need help aligning the last two elements in the card. I want the first one (a button) to be on the left, and another element (a Div with multiple social icon images) on the right side. Can someone provide guidance on how to achieve this layout? <!D ...

Set JSON Value Session

In the table, there is an option to edit certain entries using a button. I have developed a function that retrieves JSON data and populates the table with it. This process happens before any other actions. Once the data is loaded, my goal is to create a c ...

Assistance in configuring Zurb Foundation 5 for optimal integration with Laravel

As a relatively new user to Laravel with previous experience using older versions of Foundation, I am currently in the process of setting up a new Laravel project. My goal is to integrate the Foundation framework into my project, but I find myself a bit co ...