[jquery] jQuery add class .active on menu

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.

This question is related to jquery menu

The answer is


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

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

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.


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.


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

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

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


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.


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

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.


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;

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


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

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


    let path = window.location.href;
    $('#nav li a').each(function() {
        if (this.href === path) {
            $(this).addClass('activo');
        }else{
            $(this).removeClass('activo')
        }
        
    })