[javascript] Active Menu Highlight CSS

I want to highlight the current menu you have click. I'm using CSS, but it is now working.

here is my css code:

#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; }

here is my 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>

This is what I like when I hover and if the menu is active

This is what I like when I hover and if the menu is active

Hover is okay, The problem is when I after click the menu the black ground is not display


@Jonathan, I have already solve it and it is more simply than what you have gave.

this is my answer:

$(function(){
    // this will get the full URL at the address bar
    var url = window.location.href; 

    // passes on every "a" tag 
    $("#sub-header a").each(function() {
            // checks if its the same on the address bar
        if(url == (this.href)) { 
            $(this).closest("li").addClass("active");
        }
    });
});

then on my css file:

.active { background-color: #000; }
/* to override the existing css for "a" tag */
#sub-header .active a{ color: #fff; }

This question is related to javascript html jquery css

The answer is


Following @Sampson's answer, I approached it this way -

HTML:

  1. I have a div with content class in each page, which holds the contents of that page. Header and Footer are separated.
  2. I have added a unique class for each page with content. For example, if I am creating a CONTACT US page, I will put the contents of the page inside <section class="content contact-us"></section>.
  3. By this, it makes it easier for me to write page specific CSS in a single style.css.

_x000D_
_x000D_
<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>
_x000D_
_x000D_
_x000D_

CSS:

  1. I have defined a single active class, which holds the styling for an active menu.

_x000D_
_x000D_
.active {
    color: red;
    text-decoration: none;
}
_x000D_
<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>
_x000D_
_x000D_
_x000D_

JavaScript:

  1. Now in JavaScript, I aim to compare the menu link text with the unique class name defined in HTML. I am using jQuery.
  2. First I have taken all the menu texts, and performed some string functions to make the texts lowercase and replace spaces with hyphens so it matches the class name.
  3. Now, if the content class have the same class as menu text (lowercase and without spaces), add active class to the menu item.

_x000D_
_x000D_
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');
  }
});
_x000D_
.active {
  color: red;
  text-decoration: none;
}
_x000D_
<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>
_x000D_
_x000D_
_x000D_

Why I Approached This?

  1. @Sampson's answer worked very well for me, but I noticed that I had to add new code every time I want to add new page.
  2. Also in my project, the body tag is in header.php file which means I cannot write unique class name for every page.

You should refer to the current element and not all elements matching your selector.

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

});

I´d also recommend you to use CSS classes instead of setting the CSS properties this way.

That would be something like;

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

});

together with;

#mainMenu td.selected {

background-color: #EDEDED; }


Another variation with 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;
}

First, give all your links a unique id and make a css class called 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;
}

Jquery version:

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

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

Vanilla javascript version:

In order to prevent selecting too many links with document.querySelectorAll, give the parent element an id called menuLinks. Add 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>

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";
    })
}

Let's say we have a menu 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 our current url be https://demosite.com/link1.html

With the following function we can add the active class to which menu's href is in our url.

let currentURL = window.location.href;

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

Try this (Do copy and paste):

Test.html:-

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

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;
}

Maybe it is very very bad way and just for lazy person but I decided to say it.

I used PHP and bootstrap and fontawsome too

for simple I have 2 pages: 1.index and 2.create-user

put this code above your 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;
}
?>

and in menu you add <?php if($a==1){echo "active";} ?> in class for menu1 and for menu2 you 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>dashbord</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>

and add in css

.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);
}

and in js add

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

first check your work without js code to understand js code for what


As the given tag to this question is CSS, I will provide the way I accomplished it.

  1. Create a class in the .css file.

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

  2. Nav-bar will be like:

    • Home
    • Contact Us
    • About Us

NOTE: If you are already setting the style for all Nav-Bar elements using a class, you can cascade the special-case class we created with a white-space after the generic class in the html-tag.

Example: Here, I was already importing my style from a class called 'navList' I created for all list-items . But the special-case styling-attributes are part of 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>

Look how I've cascaded one class-name behind other.


Answer: You need CSS for “current” link here is tut.

Description of jQuery menu nav

Sample : One of meny solution

Its working for me


add simply way

<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');
});

});

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to css

need to add a class to an element Using Lato fonts in my css (@font-face) Please help me convert this script to a simple image slider Why there is this "clear" class before footer? How to set width of mat-table column in angular? Center content vertically on Vuetify bootstrap 4 file input doesn't show the file name Bootstrap 4: responsive sidebar menu to top navbar Stylesheet not loaded because of MIME-type Force flex item to span full row width