0

I have jquery script that will add clas to a specfic li. The first 3 li it add class but if clicking on 4th to last li it does not apply. Please help me about this:

html:

<ul class="sidebar-menu" id = "navigation">
    <li><a href="www.site.com/dashboard">Dashboard</a></li> 
    <li><a href="wwww.site.com/mycoupon">My Coupons</a></li> 
    <li><a href="www.site.com/member">View Profile</a></li>
    <li><a href="www.site.com/update">Update Profile</a></li>
</ul>

Jquery:

$(document).ready(function() {
    var  current_page = document.URL;

    if (current_page.match(/dashboard/)){
        $("ul#navigation li:eq(0)").addClass('selected sel');
    }

    else if (current_page.match(/mycoupon/)){
        $("ul#navigation li:eq(1)").addClass('selected sel');
    } 

    else if (current_page.match(/member/)){
        $("ul#navigation li:eq(2)").addClass('selected sel');
    }

    else if (current_page.match(/update/)){
        $("ul#navigation li:eq(3)").addClass('selected sel');
    } 

    else { // don't mark any nav links as selected
        $("ul#navigation li").removeClass('selected sel');
    }
});
2
  • It is working for me. Commented Aug 12, 2016 at 7:12
  • Oh in my side got stock to 3rd li only Commented Aug 12, 2016 at 7:14

1 Answer 1

1

Instead of writing code for each menu, you can simply use like this,

$(document).ready(function() {
  var current_page = document.URL;
  $("#navigation li  a").filter(function() {
    return current_page.indexOf($(this).attr("href")) > -1
  }).closest("li").addClass("selected sel");
});
Sign up to request clarification or add additional context in comments.

1 Comment

Wooh You save my day Anoop Joshi Thanks A lot

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.