Radian Radian - 4 months ago 9
jQuery Question

Compare link href with address path for menu state

I'm working on right menu and i want to save that state with compare link

href
tag with address path location.

function setNavigation() {
var path = window.location.pathname;
path = path.replace(/\/$/, "");
path = decodeURIComponent(path);
$(".sidebar-menu li ul a").each(function () {
var href = $(this).attr('href');
if (path.substring(0, href.length) === href) {
$(this).addClass('active-item');
}
});


The problem is that the code not recognize similar addresses in one
ul


for example both of below item give
active-item
class.

href="site/city/company/"
href="site/city/company/sample"


also here is my html

<li><a href="/Panel/Place" class="active-item"></a></li>
<li><a href="/Panel/Place/item" class="active-item"></a></li>
<li><a href="/Panel/Place/City"></a></li>
<li><a href="/Panel/Definitions/Attribute">/a></li>
<li><a href="/Panel/TouristDestination"></a></li>

Answer
  1. Correct : $(".sidebar-menu li ul a") to $(".sidebar-menu ul li a")

  2. I have changed the path matching method, check it out:

//sample path
var path = "www.xyz.com/Panel/Place";

function setNavigation() {
  path = path.substring(path.indexOf("/"), path.length);
  path = decodeURIComponent(path);
  $(".sidebar-menu ul li a[href='" + path + "']").addClass('active-item');
}

setNavigation();
.active-item {
  color: red;
  background-color: #aaa;
}
li a {
  display: block;
  border: 1px solid #888;
  padding: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="sidebar-menu">
  <ul>
    <li><a href="/Panel/Place">/Panel/Place</a></li>
    <li><a href="/Panel/Place/item">/Panel/Place/item</a></li>
    <li><a href="/Panel/Place/City">/Panel/Place/City</a></li>
    <li><a href="/Panel/Definitions/Attribute">/Panel/Definitions/Attribute</a></li>
    <li><a href="/Panel/TouristDestination">/Panel/TouristDestination</a></li>
  </ul>
</div>