JordanMiguel
JordanMiguel

Reputation: 740

Add active Menu or Navigation class based on URL

I've added an active class to my menu items. However my current implementation is adding the class to all list menu items as opposed to whatever the current page is.

Please let me know if there is an issue with my current code, and what I can do to achieve the desired outcome.

<ul id="menu_items">
 <li class="has-sub"><a href="/collections">STORE</a></li>
 <li><a href="/collections">RESEARCH</a></li>
 <li><a href="/collections">INFO</a></li>
</ul>

$(function(){
        var current = location.pathname;
        $('#menu_items li a').each(function(){
            var $this = $(this);
            // if the current path is like this link, make it active
            if($this.attr('href').indexOf(current) !== -1){
                $this.addClass('active');
            }
        })
    })  

.active {text-decoration:underline;}

Upvotes: 0

Views: 47

Answers (2)

tapu74
tapu74

Reputation: 1181

Okay, Try this way, hope it will work

<ul id="menu_items">
<li><a href="#index">Index</a></li>
 <li class="has-sub"><a href="#store">STORE</a></li>
 <li><a href="#research">RESEARCH</a></li>
 <li><a href="#info">INFO</a></li>
</ul>
</html>

<Script>
 $("#menu_items li").bind("click", function(e){

 $("li").click(function() {
        $(this).siblings().find("a").removeClass("active");
        $(this).find("a").addClass("active")
    })
 })

</Script>

Upvotes: 1

tapu74
tapu74

Reputation: 1181

Please Check the URLs , All the Links are "/collections"

Upvotes: 0

Related Questions