I am using my Navigation as a separate page which is Navigation.php
and I am adding this page by <?php include 'header.php'; ?>
in everypage.
But when I am going on a page, for example: going to About page, that About button in navigation bar have a class class='active'
and that class adding by javascript.
The problem is coming when I am going to 2nd level page like:
Portfolio
> Portfolio Item
That script is not adding class on Portfolio
button.
Navigation.php
page:
<ul class="nav nav-pills" id="mainNav"> <li <?php echo (basename($_SERVER['PHP_SELF']) == 'index.php') ? 'class="active"' : ''; ?>> <a class="nav-item nav" href="/home"> Home </a> </li> <li <?php echo (basename($_SERVER['PHP_SELF']) == 'about.php') ? 'class="active"' : ''; ?>> <a class="nav-item" href="/about"> About </a> </li> <li <?php echo (basename($_SERVER['PHP_SELF']) == 'services.php') ? 'class="active"' : ''; ?>> <a class="nav-item" href="/services"> Services </a> </li> <li <?php if ((basename($_SERVER['SCRIPT_FILENAME'], '.php')) == 'portfolio' or 'portfolioItem') echo "class='active'";?>> <a class="nav-item" href="/portfolio"> Portfolio </a> </li> <li <?php echo (basename($_SERVER['PHP_SELF']) == 'showcase.php') ? 'class="active"' : ''; ?>> <a class="nav-item" href="/showcase"> Showcase </a> </li> <li <?php echo (basename($_SERVER['PHP_SELF']) == 'blog.php') ? 'class="active"' : ''; ?>> <a class="nav-item" href="/blog"> Blog </a> </li> <li <?php echo (basename($_SERVER['PHP_SELF']) == 'contact.php') ? 'class="active"' : ''; ?>> <a class="nav-item" href="/contact"> Contact </a> </li> </ul>
Javascript
I’m using:
<script> $(function () { var pgurl = window.location.href.substr(window.location.href.lastIndexOf("/") + 1); $("nav-pills ul li").each(function () { if ($(this).attr("href") == pgurl) { $(this).parent().addClass('active'); } if ((($(this).attr("href") == 'index.php')||($(this).attr("href") == '')) && (pgurl == '')) { $(this).parent().addClass("active"); } }) }); </script>
Advertisement
Answer
Please try changing
<?php if ((basename($_SERVER['SCRIPT_FILENAME'], '.php')) == 'portfolio' or 'portfolioItem') echo "class='active'";?>>
to
<?php if ( (basename($_SERVER['SCRIPT_FILENAME'], '.php')) == 'portfolio.php' || (basename($_SERVER['SCRIPT_FILENAME'], '.php')) == 'portfolioItem.php' ) { echo "class='active'"; } ?>>