jQuery add class .active on menu
Asked Answered
B

16

36

I've got a problem.

I want to add the class "active" on item menu when the relative page is on.

the menu is very simple:

<div class="menu">

<ul>
<li><a href="~/link1/">LINK 1</a>
<li><a href="~/link2/">LINK 2</a>
<li><a href="~/link3/">LINK 3</a>
</ul>

</div>

In jQuery I need to check if the url is www.xyz.com/other/link1/

if it's this one I would like to add a class one the 'a' element of link1.

I'm trying many solutions but nothing work.

Bannon answered 1/2, 2011 at 18:7 Comment(0)
A
81

Click here for a solution in jsFiddle

What you need is you need to get window.location.pathname as mentioned and then create regexp from it and test it against navigation hrefs.

$(function(){

    var url = window.location.pathname, 
        urlRegExp = new RegExp(url.replace(/\/$/,'') + "$"); // create regexp to match current url pathname and remove trailing slash if present as it could collide with the link in navigation in case trailing slash wasn't present there
        // now grab every link from the navigation
        $('.menu a').each(function(){
            // and test its normalized href against the url pathname regexp
            if(urlRegExp.test(this.href.replace(/\/$/,''))){
                $(this).addClass('active');
            }
        });

});
Astonish answered 1/2, 2011 at 19:5 Comment(10)
oh ye, you are the winner! Thanks mate!Bannon
This works for me, except on the homepage. For some reason it is setting ALL the navigation links to active. Example in your jsFiddle change to var url = "/"Novotny
try to change the urlRegExp line to urlRegExp = new RegExp(url == '/' ? window.location.origin + '/?$' : url.replace(/\/$/,''));Astonish
Awesome - with the urlRegExp from the comments it works well :)Dirichlet
See alternative, a more elegant, decision: https://mcmap.net/q/427120/-using-server-side-includes-what-are-options-for-selecting-a-current-nav-elementUnreal
I tried using this method in my menu, but it doesn't work on any page URL with hyphens. For example, it works fine with /index/posts/, but doesn't work on /index/demo-page/. Any ideas? It's driving me nuts today.Palpate
So i've tried this and it works good. But when i'm on the homepage (www.foo.com/) all my links get the class active…Epigynous
@TomTu, thanks for being awesome. Is there any reason why the answer shouldn't be updated to use the other urlRegExp variable that you provided?Counterirritant
@TomTu, Jsfiddle is not working when i click on the Links, Can you look once into it.Capone
Is there a possiblity to exclude anchor links from the regex? If I have a anchor in the url all menu elements get the active class.Layne
M
22

An easier way for me was:

var activeurl = window.location;
$('a[href="'+activeurl+'"]').parent('li').addClass('active');

because my links go to absolute url, but if your links are relative then you can use:

 window.location**.pathname**
Metrorrhagia answered 12/4, 2012 at 5:36 Comment(2)
If you're going to use this with the pathname second style, make sure you do NOT include the asterisks, which I believe OP put there for emphasis but they're not rendering as such. Thus, you would want to use window.location.pathname HTH.Together
This is a great solution, I modified a little just to be sure it affects the link in the menu. Because there might be a link in the body content with same link and if the parent element is somehow a list item, this might cause a bit css issue. Or if there is a quick menu list in the footer it would be affected too. $('#primaryNav a[href="'+activeURL+'"]').parent('li').addClass('active'); This ensures it only adds the active class in my desired location.Portia
I
2

Get the LI elments, loop through, check the HREF:

$('.menu').find('a').each(function() {
    if($(this).attr('href').indexOf('www.xyz.com/other/link1/')>0) {
          $(this).addClass('active');
    }
})
Incorrigible answered 1/2, 2011 at 18:11 Comment(1)
nothing yet... what I need is to see if part of the url contains some words, if true I add the class...Bannon
L
2

Check this out this WORKS

Html

<div class="menu">

    <ul>
        <li><a href="~/link1/">LINK 1</a>
        <li><a href="www.xyz.com/other/link1">LINK 2</a>
        <li><a href="~/link3/">LINK 3</a>
    </ul>

</div>

Jquery

$(document).ready(function(){
    $(".menu ul li a").each(function(){
        if($(this).attr("href")=="www.xyz.com/other/link1")
            $(this).addClass("active");
    })
})
Lemos answered 1/2, 2011 at 18:20 Comment(1)
please elaborate Toro I can help youLemos
B
2

Wasim's answer a few posts up from here works as advertised:

http://jsfiddle.net/Realto619/jKf3F/1/

Baldachin answered 29/8, 2012 at 3:41 Comment(0)
D
2

No other "addClass" methods worked for me when adding a class to an 'a' element on menu except this one:

$(function () {
        var url = window.location.pathname,
    urlRegExp = new RegExp(url.replace(/\/$/, '') + "$");  
        $('a').each(function () {
                            if (urlRegExp.test(this.href.replace(/\/$/, ''))) {
                $(this).addClass('active');
            }
        });
    });

This took me four hours to find it.

Duck answered 5/3, 2013 at 9:19 Comment(0)
G
1

window.location.href will give you the current url (as shown in the browser address). After parsing it and retrieving the relevant part you would compare it with each link href and assign the active class to the corresponding link.

Gyrfalcon answered 1/2, 2011 at 18:10 Comment(1)
V
1

Use window.location.pathname and compare it with your links. You can do something like this:

$('a[href="~/' + currentSiteVar + '/"').addClass('active');

But first you have to prepare currentSiteVar to put it into selecor.

Vhf answered 1/2, 2011 at 18:12 Comment(0)
M
1

I am guessing you are trying to mix Asp code and JS code and at some point it's breaking or not excusing the binding calls correctly.

Perhaps you can try using a delegate instead. It will cut out the complexity of when to bind the click event.

An example would be:

$('body').delegate('.menu li','click',function(){
   var $li = $(this);

   var shouldAddClass = $li.find('a[href^="www.xyz.com/link1"]').length != 0;

   if(shouldAddClass){
       $li.addClass('active');
   }
});

See if that helps, it uses the Attribute Starts With Selector from jQuery.

Chi

Mite answered 1/2, 2011 at 18:27 Comment(2)
using asp.net yes, but not ID, everything is ok, I would like to match part of the url, in example /link1/ and if it match I will add specific class on the relative menu item (that I can call with different classes)...Bannon
Hi Toro, I have updated the sample, see if that helps. It uses the "attribute starts with" selector from jQuery.Mite
W
1

this work for me :D

    function setActive() {
      aObj = document.getElementById('menu').getElementsByTagName('a');
      for(i=0;i<aObj.length;i++) {
        if(document.location.href.indexOf(aObj[i].href)>=0) {
          var activeurl = window.location;
          $('a[href="'+activeurl+'"]').parent('li').addClass('active');
        }
      }
    }

    window.onload = setActive;
Wean answered 5/4, 2015 at 14:29 Comment(0)
G
1
<script type="text/javascript">
    jQuery(document).ready(function($) {
    var url = window.location.pathname,
urlRegExp = new RegExp(url.replace(/\/$/,'') + "$"); 
    $("#navbar li a").each(function() {//alert('dsfgsdgfd');
    if(urlRegExp.test(this.href.replace(/\/$/,''))){
    $(this).addClass("active");}
});
}); 
</script>
Gabrila answered 31/10, 2015 at 8:27 Comment(0)
D
0

Setting the active menu, they have the many ways to do that. Now, I share you a way to set active menu by CSS.

    <a href="index.php?id=home">Home</a>
    <a href="index.php?id=news">News</a>
    <a href="index.php?id=about">About</a>

Now, you only set $_request["id"] == "home" thì echo "class='active'" , then we can do same with others.

<a href="index.php?id=home" <?php if($_REQUEST["id"]=="home"){echo "class='active'";}?>>Home</a>
<a href="index.php?id=news" <?php if($_REQUEST["id"]=="news"){echo "class='active'";}?>>News</a>
<a href="index.php?id=about" <?php if($_REQUEST["id"]=="about"){echo "class='active'";}?>>About</a>

I think it is useful with you.

Diocese answered 5/7, 2013 at 3:44 Comment(1)
If we use the PHP framework, I think check current controller or action is easy. We can compare controller or action to set active link menu. I use Yii framework: Yii::app()->controller->id and Yii::app()->controller->action->idDiocese
F
0
$(function() {
     var pgurl = window.location.href.substr(window.location.href.lastIndexOf("/")+1);
     $(".nav li").each(function(){
          if($('a',this).attr("href") == pgurl || $('a', this).attr("href") == '' )
          $(this).addClass("active");
     })
});
Flowerless answered 17/9, 2016 at 0:4 Comment(0)
L
0

This works for me, basically the navigation is same

<div id="main-menu">
  <ul>
    <li><a href="<?php echo base_url();?>shop">SHOP</a>
    <li><a href="<?php echo base_url();?>events">EVENTS</a>
    <li><a href="<?php echo base_url();?>services">SERVICES</a>
  </ul>
</div>

Let's say you're at the URL : http://localhost/project_name/shop/detail_shop/

And you want the "SHOP" li link to get class "active" so you can visually indicate it's the active navigation, even if you're at the sub page of "shop" at "detail_shop".

The javascript :

var path = window.location.pathname;
var str = path.split("/");
var url = document.location.protocol + "//" + document.location.hostname + "/" + str[1] + "/" + str[2];

$('#main-menu a[href="' + url + '"]').parent('li').addClass('active');
  1. str will get ,project_name,shop,detail_shop
  2. document.location.protocol will get http:
  3. document.location.hostname will get localhost
  4. str[1] will get project_name
  5. str[2] will get shop

Essentially that will match links in the nav who's href attribute begins with "shop" (or whatever the secondary directory happens to be).

Lathi answered 28/8, 2017 at 4:50 Comment(1)
Welcome to StackOverflow! While answers are always appreciated, this question was asked 6 years ago, and already had an accepted solution. Check out the documentation on writing great answers for some tips on how to make your answers count :)Contribute
F
0
    let path = window.location.href;
    $('#nav li a').each(function() {
        if (this.href === path) {
            $(this).addClass('activo');
        }else{
            $(this).removeClass('activo')
        }
        
    })
    
Forethought answered 30/7, 2020 at 22:13 Comment(0)
P
0

This work for me

$(function(){
    var url = window.location.pathname;
    $('.menu').find(`a[href="${url}"]`).addClass('active');
)};
Prophetic answered 12/5, 2023 at 19:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.