0

I have the navigation bar as below

<ul>
  <li class="selected"><a href=">My Profile</a></li>
  <li><a href="">xxxx</a></li>
  <li><a href="">mybook</a></li>
  <li><a href="">Photos <span>4</span></a></li>
  <li><a href="">Profile List</a></li>
</ul>

I want that if the url is www.abc.com/user/profile then profile tab class should have class selected attached

If photos then photo tab.

If we can have partial match that will be good but i am not sure if thats possible

like in url i have /user/book and myBook gets selected

1
  • Are you asking about how to write a jquery selector for that? What about using something like if ( .attr("href") == "your URL") { ... Commented Jul 31, 2012 at 2:26

3 Answers 3

2

Some elegant variant:

<ul class="menu">
  <li><a class="profile" href="/user/profile">My Profile</a></li>
  <li><a class="book" href="/user/book">My Book</a></li>
</ul>

$(document).ready(function () {
  var page = document.location.href.split('/').slice(-1)[0];
  $('.menu .' + page).addClass('selected');
});
Sign up to request clarification or add additional context in comments.

Comments

0

You can grab the part you want with regex:

var userPage = /user\/(.+)/.exec(location.href)[1];

That will give you the part after user/. Then you could use a switch statement:

switch (userPage) {
  case 'profile':
    ...
    break;
  case 'book':
    ...
    break;
}

1 Comment

can't i use anything like if(href contains keyword) then return true rather than splitting the urls
0

You would want to switch off of location.pathname. Granted that you give that <ul> a class of nav:

$(function () {
    if (location.pathname.search("/user/profile") != -1) {
        // page is /user/profile
        $("#nav li").eq(0).addClass("selected");
    } else if (location.pathname.search("/user/photos") != -1) {
        // page is some/thing
        $("#nav li").eq(3).addClass("selected");
    }
    ... etc
});

Things to notice

  • We use $(function () {...}); as opposed to $(document).ready(function() {...});. It is less typing and more efficient

  • We use String.search(), which returns the index at which the string "/user/profile" appears. If the string is not found, String.search() will return -1, so if it != -1, it exists.

  • We also use jQuery.eq( index ) this treats elements selected by a jQuery selector as an array and returns the element of the specified index.

References

Check out jQuery's .eq here, and JavaScript's String.search here

Comments

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.