Rhyan Manlangit
Rhyan Manlangit

Reputation: 13

Menu active state remain on clicked link after the page reload

I'm having trouble with my menu. i want the active state to remain on the last clicked link.

<ul id="nav">
    <li class="active"><a href="?field1="2"&field2="test">products </a></li>
    <li><a href="?field1="3"&field2="test2">products2 </a></li>
</ul>

when i click on products2 the table on the right side will populate data base on the field in url this will refresh the page. how can i remain the clicked link have the active class?

Upvotes: 1

Views: 2530

Answers (4)

empiric
empiric

Reputation: 7878

The following should be working:

var qs = decodeURIComponent(location.search);
$('a[href="' + qs + '"]').parents('li').addClass('active');

In location.search you will find the query-string which is appenden to your URL.

decodeURIComponent will decode your URL so it avoids e.g. the %20 for a whitespace.

$('a[href="' + qs + '"]') selects the a -tag which has a href-attribute corresponding to your query-string.

But I would recommend to remove the extra " from your url-parameters inside your href:

<ul id="nav">
    <li class="active"><a href="?field1=2&field2=test">products </a></li>
    <li><a href="?field1=3&field2=test2">products2 </a></li>
</ul>

If you can't remove the quotation marks you have to escape them for the attribute-selector to work.


Reference

location.search

decodeURIComponent

jQuery attribute selector

.parents()

.addClass()

Upvotes: 1

Vikram Wable
Vikram Wable

Reputation: 58

Simple but ugly solution is that On the product2 page add the code to manually highlight the link.

Or if the problem is for all the links and there are n number of links will be available in future then your code should be more structured. In this case you can put the common code for handling this kind of common work (highlighting the links on side bar) in one of the common js file. Instead of putting on all the pages.

Upvotes: 0

Santanu
Santanu

Reputation: 420

Using jQuery, you can try this for your scenario.

   var currentPath="?"+window.location.href.split("?")[1];
   $("a[href='"+currentPath+"']").parent().addClass("active");

Upvotes: 0

BobbyTables
BobbyTables

Reputation: 4695

You can examine the url, and with that apply the class to the relevant element. This can be done server side, or client side (i see that you tag this with client technology)

Like this

//if url contains "field1=3" then add the class "selected" to element "tab2"
if (window.location.href.indexOf("field1=3") > -1) {
   $("#tab2").addClass("selected")
}

The values and tabs should obviously be structured in some whay, but you get the gist.

Upvotes: 0

Related Questions