Add .active class to the current page's link in a menu using jQuery or PHP
You can use jQuery to loop through all links and compare their URLs with location
. Here is an example:
$(".sf-menu a").filter(function(){
return this.href == location.href.replace(/#.*/, "");
}).addClass("active");
Add active class to link with current page
You can test this code with your real urls.
Retrieving the last valid "word" (in \abc\page1
is page1
or in \xyz\page1\
is page1
) for both url, page and menu item url. Finally I make the comparison between the two.
One more thing that would be done, remove any hashes (url\page#abc
) and parameters (url\page?Param=value
)
jQuery(function($) {
var window_location_href = 'http://your.site.com/parent/page2/';
window_location_href = window_location_href.endsWith('/') ? window_location_href.substr(0, window_location_href.length - 1) : window_location_href;
var pgurl = window_location_href.substr(window_location_href.lastIndexOf("/") + 1);
$(".menu-item > a").each(function() {
var thisPage = $(this).attr("href");
thisPage = thisPage.endsWith('/') ? thisPage.substr(0, thisPage.length - 1) : thisPage;
thisPage = thisPage.substr(thisPage.lastIndexOf("/") + 1);
if (thisPage == pgurl)
$(this).addClass("active");
});
});
.menu-link {
color: blue;
display: block;
}
.active {
color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="content">
...
<div class="menu-item">
<a href="/complexPath/parent/page1/" class="menu-link"> Page1 </a>
<a href="/complexPath/parent/page2/" class="menu-link"> Page2 </a>
<a href="/complexPath/parent/page3/" class="menu-link"> Page3 </a>
</div>
...
</div>
Add 'active' class to navigation links de
Here is how it's done in PHP.
<?php
$menu = array(
array(
'href' => 'index.php',
'text' => 'Index',
),
array(
'href' => 'test.php',
'text' => 'Test',
),
);
?>
<nav>
<ul class="menu">
<?php
foreach ($menu as $link) {
$item='<li>';
if (substr($_SERVER['REQUEST_URI'], 1) == $link['href']) {
$item.='<a href="'.$link['href'].'" class="active">'.$link['text'].'</a>';
} else {
$item.='<a href="'.$link['href'].'">'.$link['text'].'</a>';
}
$item.='</li>';
print $item;
}
?>
</ul>
</nav>
Like you can see I've used an array instead of some plain HTML, I suggest you to do the same for as many things as possible. This makes your code more "dynamic" and has many benefits.
Here is how it's done in JavaScript
<nav>
<ul class="menu">
<li><a href="index.php">Index</a></li>
<li><a href="test.php">Test</a></li>
</ul>
</nav>
<script type="text/javascript">
var menu = document.querySelectorAll('.menu li a');
for (var i = menu.length - 1; i >= 0; i--) {
if (menu[i].href==document.URL) {
menu[i].setAttribute("class", "active");
}
};
</script>
The jsfiddle
And not to forget, the jQuery of doing it..
<nav>
<ul class="menu">
<li><a href="index.php">Index</a></li>
<li><a href="test.php">Test</a></li>
</ul>
</nav>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
$('.menu li a').each(function() {
if ($(this).attr('href')==location.pathname.substr(1)){
$(this).addClass('active');
}
});
</script>
The jsfiddle
Use PHP to add active class to nav links when on page or sub-page?
I haven't tested this, but why can't you just do:
<?php
$current_page = basename($_SERVER['PHP_SELF']);
?>
and then:
<li class="<?php if ($current_page == "index.php"){ echo "active "; }?> item"><a href="index.php">Home</a></li>
for normal links, and:
<li class="<?php if ($current_page == "index.php"){ echo "active "; }?> item has-dropdown">
<a href="about.php">About Us</a>
for links with dropdowns?
Related Topics
PHP - Time Remaining Until Specific Time from Current Time of Page Load
PHP Soap Client That Understands Multi-Part Messages
How to Tell If a Timezone Observes Daylight Saving at Any Time of the Year
How to Call a Python Script from PHP
Chart.Js - Getting Data from Database Using MySQL and PHP
PHP Array VS [ ] in Method and Variable Declaration
What Is the Postman-Token Header Attribute in Generated Code from Postman
Alternative to Money_Format() Function
What Does the Dot-Slash Do to PHP Include Calls
Forcing Access to _Php_Incomplete_Class Object Properties
Codeigniter: 404 Page Not Found on Live Server
How to Match Accented Characters with PHP Preg
Using If(!Empty) with Multiple Variables Not in an Array
How to Access a Different Controller from Inside a Controller Symfony2