I have a dynamic navigation bar that stores the pages/URLs in a database. The nav.php is the script that handles displaying and running through the SQL queries to display the links. I'm having a difficult time adding a script that adds an active class to the links.
My page URLs are as follows:
- /page/2/full-service-fleet
- /rate-request
- /employment
- /page/5/links
- /page/6/contact
PHP:
<nav>
<?php
while ($row = $result->fetch_assoc())
{
$navid = $row['id'];
$navname = $row['nav'];
$navslug = $row['slug'];
$navurl = $row['url'];
$navnum = $row['num'];
if ($navurl != ''){
$navlink = $navurl;
}
else{
$navlink = "page.php?id=".$navid."&title=".$navslug;
}
if (substr($navlink,0,4) != "http"){
if ($server_name <> "") {
$navlink = "http://".$server_name."/".$navlink;
}
}
if ($navurl == '#'){
$navlink = $navurl;
}
if ($navnum ==0){
?>
<a href="<?php echo $navlink; ?>"><?php echo $navname; ?></a>
<?php
}else{
?>
<!-- the rest isn't necessary -->
......
</nav>
The actual links that are being displayed is this line:
<a href="<?php echo $navlink; ?>"><?php echo $navname; ?></a>
JS Script:
jQuery(document).ready(function($){
// Get current path and find target link
var path = window.location.pathname.split("/").pop();
// Account for home page with empty path
if ( path == '' ) {
path = 'index.php';
}
var target = $('nav a[href="'+path+'"]');
// Add active class to target link
target.addClass('active');
});