I have a separate navigation php which has a list of links and menu options:
echo "<ul id='menu'>";
//some if loop to do the following:
echo "<li><a href='#'>Adminstration</a>
<ul><li>";
if($userm == 'R'||$userm == 'RW') {
echo "<a href='/N.Jain/administration/usermanagement.php>User Management</a>";
}
This file has 10 such sub-menu. What i am trying to achieve here is that if a User is on this particular page, then the menu should expand and highlight that option.
Here is my menu javascript:
function initMenu() {
$('#menu ul').hide();
$('#menu li a').click(
function() {
var checkElement = $(this).next();
if((checkElement.is('ul')) && (checkElement.is(':visible'))) {
$('#menu ul:visible').slideUp('normal');
return false;
}
if((checkElement.is('ul')) && (!checkElement.is(':visible'))) {
$('#menu ul:visible').slideUp('normal');
checkElement.slideDown('normal');
return false;
}
}
);
}
Now i am trying to get the link and then set its class to active and then do something:
function markActiveLink() {
$("#menu li ul li a").filter(function() {
var currentURL = window.location.toString().split("/");
return $(this).attr("href") == currentURL[currentURL.length-1];
}).addClass("active");
if($('#menu li ul li a').hasClass('active') == true) {
console.log('has');
}
}
attr('href')gives only the attribute value whatever you have set on the anchorhrefattribute. If you usehrefproperty of anchor element usingprop('href')then it will give you the complete url. And then you can compare the complete url instead of spliting and trying the compare part of the url. Try this.Note I am converting both the
hrefandlocationto upper case just to avoid case sensitive comparison.prop()– Gets the value of a property for the first element in the set of matched elements.