26

In a page with some navigation links,I want the link of the current page are hightlighted,just like this:

alt text

The link "HTML Attributes" is highlighted(bolded) since this link will take one to the current page.

I know this can be implemented manually(just hightlighted the according link,but is there some smart way? highlight the right link dynamically and automatically?

Community
  • 1
  • 1
hguser
  • 35,079
  • 54
  • 159
  • 293
  • Not in HTML or CSS alone. You need JavaScript or a server-side control to implement this in a truly dynamic way. – TylerH Jun 16 '23 at 20:31

13 Answers13

53

CSS:

.topmenu ul li.active a, .topmenu ul li a:hover {
    text-decoration:none;
    color:#fff;
    background:url(../images/menu_a.jpg) no-repeat center top;
}

JavaScript:

<script src="JavaScript/jquery-1.10.2.js" type="text/javascript"></script> 

<script type="text/javascript">
    $(function() {
        // this will get the full URL at the address bar
        var url = window.location.href;

        // passes on every "a" tag
        $(".topmenu a").each(function() {
            // checks if its the same on the address bar
            if (url == (this.href)) {
                $(this).closest("li").addClass("active");
                //for making parent of submenu active
               $(this).closest("li").parent().parent().addClass("active");
            }
        });
    });        
</script>

Html Code:

<div class="topmenu">
    <ul>
        <li><a href="Default.aspx">Home</a></li>
        <li><a href="NewsLetter.aspx">Newsletter</a></li>
        <li><a href="#">Forms</a></li>
        <li><a href="#">Mail</a></li>
        <li><a href="#">Service</a></li>
        <li style="border:none;"><a href="#">HSE</a></li>
        <li><a href="#">MainMenu2</a>
           <ul>
              <li>submenu1</li>
              <li>submenu2</li>
              <li>submenu3</li>
          </ul>
       </li>
    </ul>
</div>
Rohan Khude
  • 4,455
  • 5
  • 49
  • 47
Raj
  • 800
  • 7
  • 8
33

You can set the id of the body of the page to some value that represents the current page. Then for each element in the menu you set a class specific to that menu item. And within your CSS you can set up a rule that will highlight the menu item specifically...

That probably didn't make much sense, so here's an example:

<body id="index">
<div id="menu">
 <ul>
  <li class="index"     ><a href="index.html">Index page</a></li>
  <li class="page1"     ><a href="page1.html">Page 1</a></li>
 </ul>
</div> <!-- menu -->
</body>

In the page1.html, you would set the id of the body to: id="page1".

Finally in your CSS you have something like the following:

#index #menu .index, #page1 #menu .page1 {
  font-weight: bold;
}

You would need to alter the ID for each page, but the CSS remains the same, which is important as the CSS is often cached and can require a forced refresh to update.

It's not dynamic, but it's one method that's simple to do, and you can just include the menu html from a template file using PHP or similar.

icabod
  • 6,992
  • 25
  • 41
  • Sounds like a good idea,simple. But how to alert the id each page? In the server side? – hguser Jan 07 '11 at 15:06
  • For one of my own sites the pages were static html - this method just made updates simpler (as the menu was in an included file I only needed to alter it once if I added a new page). However, yes you would need some way to set the body id on the server-side. How you do this depends greatly on how you run your site. My Wordpress blog, for example, uses a theme that sets a `class` in the body tag according to what page is being viewed. – icabod Jan 07 '11 at 15:18
  • 1
    This approach means you have to have a body element in every view. Not very elegant. You would almost certainly need JS to do this dynamically. jQuery makes it pretty easy. Look at my answer below. –  Apr 04 '13 at 18:15
  • @kevinx007 - what do you mean by "view"? The body _tag_, while technically being optional, is _usually_ included in well-formed html, so it shouldn't be a problem in most cases, unless you're prototyping and decide not to explicitly specify the elements using tags. – icabod Apr 05 '13 at 09:16
  • Regarding View, I meant an MVC view. In the scenario where there is one base layout containing your body tag and you have different views which don't have body tags. But my answer may have been too specific with technology, the question was regarding only HTML. –  Apr 07 '13 at 19:33
3

It seems to me that you need current code as this ".menu-current css", I am asking the same code that works like a charm, You could try something like this might still be some configuration

a:link, a:active {
    color: blue;
    text-decoration: none;
}

a:visited {
    color: darkblue;
    text-decoration: none;
}

a:hover {
    color: blue;
    text-decoration: underline;
}

div.menuv {
    float: left;
    width: 10em;
    padding: 1em;
    font-size: small;
}


div.menuv ul, div.menuv li, div.menuv .menuv-current li {
    margin: 0;
    padding: 0;
    list-style: none;
    margin-bottom: 5px;
    font-weight: normal;
}

div.menuv ul ul {
    padding-left: 12px;
}

div.menuv a:link, div.menuv a:visited, div.menuv a:active, div.menuv a:hover {
    display: block;
    text-decoration: none;
    padding: 2px 2px 2px 3px;
    border-bottom: 1px dotted #999999;
}

div.menuv a:hover, div.menuv .menuv-current li a:hover {
    padding: 2px 0px 2px 1px;
    border-left: 2px solid green;
    border-right: 2px solid green;
}

div.menuv .menuv-current {
    font-weight: bold;
}

div.menuv .menuv-current a:hover {
    padding: 2px 2px 2px 3px;
    border-left: none;
    border-right: none;
    border-bottom: 1px dotted #999999;
    color: darkblue;
}
Mareno
  • 67
  • 2
1
<script id="add-active-to-current-page-nav-link" type="text/javascript">
    function setSelectedPageNav() {
        var pathName = document.location.pathname;
        if ($("nav ul li a") != null) {
            var currentLink = $("nav ul li a[href='" + pathName + "']");
            currentLink.addClass("active");
        }
    }
    setSelectedPageNav();
</script>
  • That possibly wouldn't work if you were working in a subdirectory, but your menu used relative links - for example, if your page was at `example.com/site/`, it would be perfectly valid for all of your links to be `a.html`, `b.html`, etc, but the pathname would be `/site/a.html`, which wouldn't match? – icabod Apr 05 '13 at 09:36
  • This would/does work fine if your menu links are full path and not relative. It is just using a jquery selector to find an element with the same link as the page you are on inside your nav element. Why do you say it wouldn't work? In the example above as long as your link elements href="/site/a.html" it would work. –  Apr 07 '13 at 19:40
  • As you mention, it would require your paths to be full, not relative. That's not an issue per se, but could make development a pain. If developing on Windows in, say, `C:\webdev\site1`, and loading the file direct into a browser rather than via a configured httpd, `document.location.pathname` gives for example `/C:/webdev/site1/index.html`. Relying on a full pathname can cause all sorts of issues, when relative paths will work just as well, while providing portability. – icabod Apr 08 '13 at 09:59
1

Css classes are here

<style type="text/css">
.mymenu
{
    background-color: blue;
    color: white;
}
.newmenu
{
    background-color: red;
    color: white;
}
</style>

Make your HTML like this, Set url as id

  <div class="my_menu" id="index-url"><a href="index-url">Index</a></div>
  <div class="my_menu" id="contact-url"><a href="contact-url">Contac</a></div>

Here write javascript, put this javascript after the HTML code.

    function menuHighlight() {
       var url = window.location.href;
       $('#'+tabst).addClass('new_current');
    }
    menuHighlight();
saravanabawa
  • 1,607
  • 1
  • 16
  • 23
0

I usually use a class to achieve this. It's very simple to implement to anything, navigation links, hyperlinks and etc.

In your CSS document insert:

.current,
nav li a:hover {
   /* styles go here */
   color: #e00122;
   background-color: #fffff;
}

This will make the hover state of the list items have red text and a white background. Attach that class of current to any link on the "current" page and it will display the same styles.

Im your HTML insert:

<nav>
   <ul>
      <li class="current"><a href="#">Nav Item 1</a></li>
      <li><a href="#">Nav Item 2</a></li>
      <li><a href="#">Nav Item 3</a></li>
   </ul>
</nav>
David Berning
  • 381
  • 1
  • 2
  • 8
0

Please Look at the following:

Here is what's working:

1.) top menu buttons are visible and highlight correctly

2.) sub menu buttons are not visible until top menu is clicked

Here is what needs work:

1.) when sub menu is clicked, looking for new page to keep the selected sub menu open (i will highlight the selected sub menu button for further clarification on navigation)

Please see code here: http://jsbin.com/ePawaju/1/edit

or here: http://www.ceramictilepro.com/_6testingonly.php#

<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>

Do I need to put this script in the head section? Where is the best place?

<div class="left">
<nav class="vmenu">
    <ul class="vnavmenu">
        <li data-ref="Top1"><a class="hiLite navBarButton2" href="#">Home</a>
        </li>
    </ul>
    <ul class="Top1 navBarTextSize">
        <li><a class="hiLite navBarButton2_sub" href="http://www.ceramictilepro.com/_5testingonly.php">sub1</a>
        </li>
        <li><a class="hiLite navBarButton2_sub" href="http://www.ceramictilepro.com/_5testingonly.php">sub2</a>
        </li>
        <li><a class="hiLite navBarButton2_sub" href="http://www.ceramictilepro.com/_5testingonly.php">sub3</a>
        </li>
        <li><a class="hiLite navBarButton2_sub" href="http://www.ceramictilepro.com/_5testingonly.php">sub4</a>
        </li>
    </ul>
    <ul class="vnavmenu">
        <li data-ref="Top2"><a class="hiLite navBarButton2" href="#">Repairs</a>
        </li>
    </ul>
    <ul class="Top2 navBarTextSize">
        <li><a class="hiLite navBarButton2_sub" href="http://www.ceramictilepro.com/_5testingonly.php">1sub1</a>
        </li>
        <li><a class="hiLite navBarButton2_sub" href="http://www.ceramictilepro.com/_5testingonly.php">2sub2</a>
        </li>
        <li><a class="hiLite navBarButton2_sub" href="http://www.ceramictilepro.com/_5testingonly.php">3sub3</a>
        </li>
        <li><a class="hiLite navBarButton2_sub" href="http://www.ceramictilepro.com/_5testingonly.php">4sub4</a>
        </li>
    </ul>
</nav>

JQuery is new to me, any help would greatly be appreciated :) var submenu;

$('.vnavmenu li').click(function () {
var elems = $('.vmenu ul:not(.vnavmenu)').length;
var $refClass = $('.' + $(this).attr('data-ref'));
var visible = $refClass.is(':visible');

$('.vmenu ul:not(.vnavmenu)').slideUp(100, function () {

    if (elems == 1) {
        if (!visible) $refClass.slideDown('fast');
    }

    elems--;
});

if (visible) $('#breadcrumbs-pc').animate({
    'margin-top': '0rem'
}, 100);
else $('#breadcrumbs-pc').animate({
    'margin-top': '5rem'
}, 100);
});
user2844139
  • 27
  • 1
  • 6
0

I would normally handle this on the server-side of things (meaning PHP, ASP.NET, etc). The idea is that when the page is loaded, the server-side controls the mechanism (perhaps by setting a CSS value) that is reflected in the resulting HTML the client sees.

Didaxis
  • 8,486
  • 7
  • 52
  • 89
0

You can use Javascript to parse your DOM, and highlight the link with the same label than the first h1 tags. But I think it is overkill =)

It would be better to set a var wich contain the title of your page, and use it to add a class at the corresponding link.

Habax
  • 1,274
  • 17
  • 26
  • Hi Habax; remember that you are answering an old question, so the original question's author has probably long ago solved their problem one way or another. For your answer to be useful, it should be a good answer for other readers searching the site for solutions to similar problems; so I recommend adding a lot more explanation and detail, perhaps with links to official documentation, to really justify why this technique is the best solution to this kind of problem. – Vince Bowdren Nov 30 '16 at 13:56
0

JavaScript:

<script type="text/javascript">
    $(function() { 
        var url = window.location;
        $('ul.nav a').filter(function() {
            return this.href == url;
        }).parent().parent().parent().addClass('active');
    });   
</script>

CSS:

.active{
    color: #fff;
    background-color: #080808;
}

HTML:

<ul class="nav navbar-nav">
                        <li class="dropdown">
                            <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="true"><i class="glyphicon glyphicon-user icon-white"></i> MY ACCOUNT <span class="caret"></span></a>
                            <ul class="dropdown-menu" role="menu">
                                <li>
                                    <?php echo anchor('myaccount', 'HOME', 'title="HOME"'); ?>
                                </li>
                                <li>
                                    <?php echo anchor('myaccount/credithistory', 'CREDIT HISTORY', 'title="CREDIT HISTORY"'); ?>
                                </li>
                          </ul>
                     </li>
</ul>
Sapna
  • 1
  • 1
0

I prefer to keep code as short and plain as possible, and avoid using any external files (jquery included). So here is what I've ended up with for myself after researching several topics - using plain Javascript and CSS, no need for jquery.

Put javascript code right after the menu finishes (after closing ul, div, whatever) - code from a snippet should be between <script>Copy code here</script> That would allow for a script to execute right after menu will be loaded. If you want to call it as a function on page load, then link will change only after all elements (including images) are loaded – place this code in a function, call it on page load, the code itself put before the closing tag like so:

<script>
    function highlightCurrentURL() {
      var a = document.getElementById("navig").getElementsByTagName("a");
      for (var i = 0; i < a.length; i++) {
        if (a[i].href.split("#")[0] == document.location.href.split("#")[0]) {
          a[i].className = "current";
        }
      }
    }
    // 
    window.onload = function() {
      highlightCurrentURL();
    }
</script>

// restrict search to a parent with specific ID (main), rather than search in the whole document
var a = document.getElementById("navig").getElementsByTagName("a");
console.log("Current URL: ", document.location.href.split("#")[0]);
console.log("Links found in HTML: ");
for (var i = 0; i < a.length; i++) {
  // for debugging you can check all found URLs in console (accessible in development mode) and delete next line after debugging
  console.log(a[i].href);
  // strip off any local (withing page) anchors (symbol "#" and what follows after)
  if (a[i].href.split("#")[0] == document.location.href.split("#")[0]) {
    // add a class to the matched link (<a>), define it in CSS
    a[i].className = "current";
  }
}
nav#navig a.current {
  color: red;
}
<nav id="navig">
  <ul>
    <li><a href="/url1">url1 name</a></li>
    <li><a href="/url2">url2 name</a></li>
    <li><a href="/url3">url3 name</a></li>
    <li><a href="https://stacksnippets.net/js#test_page_anchor">Test link matching current URL</a></li>
  </ul>
</nav>
Vadim
  • 3
  • 2
  • This question was asked 10 years ago on an older version of html – ParkerAucoin Apr 10 '21 at 22:31
  • [link](#comment68994017_4626537) - as was mentioned in a comment by Vince, it is an old question and any further updates are for people like me, not the topicstarter. So update should be more general and helpful for others. Wasn't mine like that? I'm new to writing here, so apologies if I did sth wrong. Just be more specific about my mistake, so that I wouldn't repeat it. And wasn't my way available 10 years ago? – Vadim Apr 12 '21 at 02:19
0

You can Implement this in various ways usinh PHP or Jquery. Here is how I have implemented it in my Projects.

<?php 
    //set a default value when the page is not an active page  

    $dashboard_active=$profile_active=$home_active='inactive_page';
    
    //get the Name of the current page;
    //in simple php set the NAME of the php file similar to the link variable
    //example set page name as home if you are going to print the variable $home/$home_active

    $page = pathinfo($_SERVER['PHP_SELF'], PATHINFO_FILENAME);

    //OR
    //in Laravel

    $page=Route::currentRouteName();
    
    //OR
    //send page value from the controller
    

    ${$page."_active"} = 'active_page';

//the above method will change the value of the current active page variable

        ?>

In html print the php data

<ul class="nav navbar-nav ">
<li ><a href="www.p.com/dashboard"><span class=" <?php echo $dashboard_active ?> ">  Dashboard</span></a></li>
<li ><a href="www.p.com/profile"><span class=" <?php echo $profile_active ?>"> Profile</span></a></li>
<li ><a href="www.p.com/home"><span class=" <?php echo $home_active ?>">Home</span></a></li>
</ul>

YOu can also do this with Jquery

<script>
    //with jquery
$(function(){
    //works when your href is an absolute href instead of relative href
        $('a').each(function(){
            if ($(this).prop('href') == window.location.href) {                
                $(this).children('span').addClass('active_page');  
                //to make the link only active
                $(this).addClass('active_page');   
                //to make the list active 
                $(this).panrent('li').addClass('active_page');   
            }
        });
    });
</script>

IN the CSS you need to add this

<style>    
.active_page:hover,.inactive_page:hover
{
  background-color: rgb(218, 119, 5)!important;
    color: white;
}
.active_page
{
  background-color: green!important;
    color: white!important;      
}

.inactive_page
{
    color:#fff;    
}
</style>
Prakhar Gyawali
  • 527
  • 4
  • 18
0

Using CSS only. You can use CSS Attribute selector to select an appropriate link for every page.

For example about.html will look like this.

CSS

a[href="/about"] {
    font-weight: bold;
}

HTML

<nav>
    <a href="/about">About</a>
    <a href="/contact">Contact</a>
</nav>
Kirill Kovalevskiy
  • 1,942
  • 2
  • 11
  • 8