I want to add class active to the <li>
whenever specific url is accessed?
my code look like this,
<ul>
<li>
<a href="link1">Link1</a>
</li>
<li>
<a href="link2">Link2</a>
</li>
<li>
<a href="link3">Link3</a>
</li>
<li>
<a href="link4">Link4</a>
</li>
<li>
<a href="link5">Link5</a>
</li>
<li>
<a href="link6">Link6</a>
</li>
</ul>
if www.abc/link1 is is present in the url then only 1st li should be active and rest of them should not have any class.
Thnks in advance
Here is how you could do it with JavaScript...
var normalisePath = function(path) { return path.replace(/^\/|\/$/g, ''); },
var path = normalisePath(window.location.pathname),
li = document.getElementsByTagName('li'),
i, length, a;
for (i = 0, length = li.length; i < length; i++) {
a = li[i].getElementsByTagName('a')[0];
if (normalisePath(a.pathname) == path) {
li[i].className += ' active';
break;
}
}
Using jQuery, you can use:
$("li").addClass("active");
You have to develop the logical part though...
EDIT: ...which is below:
$(function() {
$("li").removeClass("active");
var current = window.location.pathname.split('/').pop();
$('a[href="' + current + '"]').addClass("active");
});
check
var path = window.location.pathname
and compare it to your li
s. Add the active
class to the one li
whose a
s href is matching path
.
Simply add a variable to the url which goes along with each page
www.abc/link1?link_num=1
Then
switch($_GET[link_num]){
case '1':
$style1 = 'class=active';
break;
case '2';
$style2 = 'class=active';
break;
etc...
}
then
<ul>
<li>
<a href="link1?link_num=1" <?=$style1?>>Link1</a>
</li>
<li>
<a href="link2?link_num=1" <?=$style2?>>Link2</a>
</li>
<li>
etc
there's a better way i'm sure but this will do it