Alex Sarnowski
Alex Sarnowski

Reputation: 739

Add class="active" to active page using PHP

Dynamic Header, CSS Class Change To Active USING PHP (dirrectory)

I want the class of the <li> tag to change under the active dirrectory... now, every guide shows me how to do it when your page equals it, but i want to change the <li> depending on what dirrectory im on

for example:

if say im on
http://example.com/RESOURCES/code/opensource,
or
http://example.com/RESOURCES/images/clipart
i want the "RESOURCES" ^^ <li> to be 'class="active"' while the rest display 'class="noactive"'

or if im on
http://example.com/tutorials/css/flawless-dropdown-menu
I want the "tutorials" <li> to be 'class="active"' while the rest are 'class="noactive"'


URL Setup:

This is my example of how my url's are displayed...

http://example.com/tutorials/css/flawless-dropdown-menu

^^That URL is the page of a tutorial....under the "tutorials" directory, than under the "CSS" category directory, than the page title (all of these directories are not real and are rewrites from .htaccess) [irrelevant]


Navigation Setup:

<ul id="mainnav">
  <li class="noactive"><a href="/">Home</a></li>
  <li class="active"><a href="/tutorials/">Tutorials</a></li>
  <li class="noactive"><a href="/resources/">Resources</a></li>
  <li class="noactive"><a href="/library/">Library</a></li>
  <li class="noactive"><a href="/our-projects/">Our Projects</a></li>
  <li class="noactive"><a href="/community/">Community</a></li>
</ul>

Upvotes: 12

Views: 99116

Answers (14)

Pistone Sanjama
Pistone Sanjama

Reputation: 561

This answer will apply if all your pages have a php extension and you want a long messy way. I put the code below on top of every php page giving each page an ID which means all pages will have an ID which is tiresome and boring and hard to track.

<?php $page = 1; ?>

Now in my header or navigation I used the code below to put the active class. You can also put an else if you want something else.

   <nav id="navbar" class="navbar">
    <ul>

      <li class="<?php if($page == 1){ echo "active"; } ?>"><a class="url" href="index.php">Index</a></li>
      <li class="<?php if($page == 2){ echo "active"; } ?>"><a class="url" href="single-post.php">Information</a></li>
      <li class="<?php if($page == 3){ echo "active"; } ?>"><a class="url" href="single-post.php">Wanted</a></li>
      <li class="<?php if($page == 4){ echo "active"; } ?>"><a class="url" href="single-post.php">Workshop</a></li>
      <li class="<?php if($page == 5){ echo "active"; } ?>"><a class="url" href="gallery.php">Gallery</a></li>
      <li class="<?php if($page == 6){ echo "active"; } ?>"><a class="url" href="featured.php">Featured</a></li>
      <li class="<?php if($page == 7){ echo "active"; } ?>"><a class="url" href="contact.php">Contact Us</a></li>

    </ul>
  </nav>

Upvotes: 1

vikas pandey
vikas pandey

Reputation: 17

You can use str_replace for this.

$path = $_SERVER['REQUEST_URI']; 
$active = str_replace('/','', $path);
<ul>
 <li class="nav-item <?php if($active == '' || $active == 'index.php'){echo 'active';}?>">
  <a class="nav-link" href="index.php">HOME</a>
 </li>
 <li class="nav-item <?php if($active == 'about.php'){echo 'active';}?>">
  <a class="nav-link" href="about.php">ABOUT US</a>
 </li>
</ul>

Upvotes: 0

vikas pandey
vikas pandey

Reputation: 17


$getUrl = $_SERVER['REQUEST_URL']; -> www.example.com/home.php

$getFileName = explode('/',$getUrl);

The result of $getFileName Will Be In Array ->[" ","home.php"]

$result = $getFileName[2]; //home.php
<li class="<?php if ($result=='' || $result == 'index.php') {echo 'active'; }?>"><a href='#'>Home</a></li>
<li class="<?php if ($result=='about.php') {echo 'active'; }?>"><a href='#'>About Us</a></li>
<li class="<?php if ($result=='contact.php') {echo 'active'; }?>"><a href='#'>Contact Us</a></li>

Upvotes: 0

kexxcream
kexxcream

Reputation: 5933

Here is another take using PHP:

<ul class="navbar-nav">
    <?php
        // Defines all pages in navigation
        $pages = array(
            'Home'     => 'index.php',
            'Products' => 'products.php',
            'Services' => 'services.php',
            'Contact'  => 'contact.php',
            'About'    => 'about.php'
        );

        // Gets active page URL
        $active = basename($_SERVER['PHP_SELF']);
        
        // Loops through all pages
        foreach ($pages as $title => $url) {
            // Checks if active url is matched and adds active CSS class
            if ($active === $url) {
                echo '<li><a href="'.$url.'" class="nav-link active">'.$title.'</a></li>';
            } 
            // Prints out default style for remaining links
            else {
                echo '<li><a href="'.$url.'" class="nav-link">'.$title.'</a></li>';
            }
        }
    ?>
</ul>

Upvotes: 1

Samir Prajapati
Samir Prajapati

Reputation: 36

Here we can do a simple thing also :

<li class="page-scroll <?php if(basename($_SERVER['PHP_SELF'])=="aboutus.php"){echo "active";} ?>"><a href="aboutus.php">About us</a></li>

Upvotes: 0

Vijay Chauhan
Vijay Chauhan

Reputation: 1312

 Try the following:

<ul class="sub-menu"> 
   <div class="h-10"></div>
   <li class="<?php if ($your_variable=="test") {echo "active"; } 
     else{echo"noactive";}?>">
     <a href="test.php">Test </a>
   </li>
    <li class="<?php if ($your_variable=="test2") {echo "active"; 
      } else {echo"noactive";}?>">
     <a href="test2.php" >Test2</a>
    </li>
    <li class="<?php if ($your_variable=="test3") {echo 
     "active"; } else  {echo "noactive";}?>">
        <a href="test3.php">Test3</a>
    </li>
 </ul>

 **strong PHP text**

 <?php 
  $directoryURI = $_SERVER['REQUEST_URI'];
   $path = parse_url($directoryURI, PHP_URL_PATH);
   $components = explode('/', $path);
   $your_variable = basename($_SERVER['PHP_SELF'], ".php"); 
  ?> 

Upvotes: 0

"includes/header.php" - This goes in Top of the File

<?php 
$activePage = basename($_SERVER['PHP_SELF']);

$index="";
$nosotros="";
$cursos="";
$contacto="";

switch ($activePage) {
    case 'index.php':
        $index=' class="current"';
        break;
    case 'nosotros.php':
        $nosotros=' class="current"';
        break;
    case 'cursos.php':
        $cursos=' class="current"';
        break;
    case 'contacto.php':
        $contacto=' class="current"';
        break;
    default:

        break;
     }
?>

and this goes on the nav section

<ul>
    <?php 
        echo '<li'.$index.'><a href="/"><div>Inicio</div></a></li>';
        echo '<li'.$nosotros.'><a href="nosotros"><div>Nosotros</div></a></li>';
        echo '<li'.$cursos.'><a href="cursos"><div>Cursos</div></a></li>';
        echo '<li><a href="http://www.redtechacademy.com"><div>Academia</div></a></li>';
        echo '<li><a href="https://www.redtechhackingshop.com"><div>Tienda</div></a></li>';
        echo '<li'.$contacto.'><a href="contacto"><div>Contacto</div></a></li>';
    ?>
</ul>

Upvotes: 0

kealaxshan
kealaxshan

Reputation: 352

if you use mysql_fetch defined your row for menu title. if we take your menu title is MENU in mysql database and you have to put in (Home,tutorials,library,resources,our-projects,community)

    <?php
//connect your data bass

 include(connection.php');

//get your from ID like www.google?id=1 

 $id = $_GET['id'];
    $query = "select * from pages where id='$id'";
    $query1 = mysql_query($query);
    while($row= mysql_fetch_array($query1))
    {
        ?>


<html>
<?php $active= $row['MENU'];?>
<ul>
  <li class="<?php if($active=='Home'){echo 'active';}else{echo'noactive';}?>"><a href="/">Home</a></li>
  <li class="<?php if($active=='tutorials'){echo 'active';}else{echo'noactive';}?>"><a href="/tutorials/">Tutorials</a></li>
  <li class="<?php if($active=='resources'){echo 'active';}else{echo'noactive';}?>"><a href="/resources/">Resources</a></li>
  <li class="<?php if($active=='library'){echo 'active';}else{echo'noactive';}?>"><a href="/library/">Library</a></li>
  <li class="<?php if($active=='our-projects'){echo 'active';}else{echo'noactive';}?>"><a href="/our-projects/">Our Projects</a></li>
  <li class="<?php if($active=='community'){echo 'active';}else{echo'noactive';}?>"><a href="/community/">Community</a></li>
</ul>
</html>
<?php };?>

Upvotes: 1

vlycser
vlycser

Reputation: 408

header.php

$activePage = basename($_SERVER['PHP_SELF'], ".php");

nav.php

<ul>
    <li class="<?= ($activePage == 'index') ? 'active':''; ?>"><a href="/index.php">Home</a></li>
    <li class="<?= ($activePage == 'tutorials') ? 'active':''; ?>"><a href="/tutorials.php">Tutorials</a></li>
...

Upvotes: 23

sachin
sachin

Reputation: 1

<?php  $request_uri= $_SERVER['REQUEST_URI'];?>
<ul>
 <li class="<?php if((strpos($request_uri,"index.html")!==false) || $request_uri=="" || $request_uri=="/"){echo "selected";}?>"><a href="/index.html">Home</a></li>

                <li class="<?php if((strpos($request_uri,"service")!==false)){echo "selected";}?>"><a href="/services.html">Services</a> </li>
<li class="<?php if((strpos($request_uri,"product")!==false)){echo "selected";}?>"><a href="/products.html">Products</a></li>
                <li class="<?php if((strpos($request_uri,"blog")!==false)){echo "selected";}?>"><a href="/blog.html">Blog</a></li>
                <li class="<?php if((strpos($request_uri,"question")!==false)){echo "selected";}?>"><a href="/question-answers.html">Ques & Ans</a></li>
                <li class="<?php if((strpos($request_uri,"career")!==false)){echo "selected";}?>"><a href="/career.html">Career</a></li>
                <li class="<?php if((strpos($request_uri,"about-us")!==false)){echo "selected";}?>"><a href="/about-us.html">About</a></li>

</ul>

Upvotes: -1

Alex Sarnowski
Alex Sarnowski

Reputation: 739

Figured out the ANSWER...I was over thinking it.

HTML

<ul id="mainnav">
    <li class="<?php if ($first_part=="") {echo "active"; } else  {echo "noactive";}?>"><a href="#">Home</a></li>
    <li class="<?php if ($first_part=="tutorials") {echo "active"; } else  {echo "noactive";}?>"><a href="#">Tutorials</a></li>
    <li class="<?php if ($first_part=="resources") {echo "active"; } else  {echo "noactive";}?>"><a href="#">Resources</a></li>
    <li class="<?php if ($first_part=="library") {echo "active"; } else  {echo "noactive";}?>"><a href="#">Library</a></li>
    <li class="<?php if ($first_part=="our-projects") {echo "active"; } else  {echo "noactive";}?>"><a href="#">Our Projects</a></li>
    <li class="<?php if ($first_part=="community") {echo "active"; } else  {echo "noactive";}?>"><a href="#">Community</a></li>
</ul>

PHP

<?php 
$directoryURI = $_SERVER['REQUEST_URI'];
$path = parse_url($directoryURI, PHP_URL_PATH);
$components = explode('/', $path);
$first_part = $components[1];
?>

Upvotes: 22

Rick Calder
Rick Calder

Reputation: 18685

It's probably easier to do with jQuery but this works:

$url='http://example.com/tutorials/css/flawless-dropdown-menu';//pass the current url here instead of a static string.
$segments = explode ("/",$url);

$menuItems=array('Tutorials','Resources', 'Library', 'Our-Projects','Community');


$menu=array();
foreach ($menuItems as $menuItem) {
if($segments[3]==strtolower($menuItem)){
    $menu[]=('<li class="active"><a href="/'.strtolower($menuItem).'/">'.str_replace("-"," ",$menuItem).'</a></li>');

} else {
    $menu[]=('<li class="no-active"><a href="/'.strtolower($menuItem).'/">'.str_replace("-"," ",$menuItem).'</a></li>');
}
}
foreach ($menu as $item) {
echo $item.'<br />';
}

Upvotes: 1

Sean
Sean

Reputation: 12433

Through PHP you can try -

<?php 
// gets the current URI, remove the left / and then everything after the / on the right
$directory = explode('/',ltrim($_SERVER['REQUEST_URI'],'/'));

// loop through each directory, check against the known directories, and add class   
$directories = array("index", "tutorials","resources","library","our-projects","community"); // set home as 'index', but can be changed based of the home uri
foreach ($directories as $folder){
$active[$folder] = ($directory[0] == $folder)? "active":"noactive";
}
?>

<ul>
  <li class="<?php echo $active['index']?>"><a href="/">Home</a></li>
  <li class="<?php echo $active['tutorials']?>"><a href="/tutorials/">Tutorials</a></li>
  <li class="<?php echo $active['resources']?>"><a href="/resources/">Resources</a></li>
  <li class="<?php echo $active['library']?>"><a href="/library/">Library</a></li>
  <li class="<?php echo $active['our-projects']?>"><a href="/our-projects/">Our Projects</a></li>
  <li class="<?php echo $active['community']?>"><a href="/community/">Community</a></li>
</ul>

Upvotes: 7

David M&#252;ller
David M&#252;ller

Reputation: 5351

Maybe this helps you:

$(document).ready(function()
{
    var parts = document.URL.split("/");
    // [http:, empty, your domain, firstfolder]
    var firstFolder = parts[3];

    $("#mainnav li").attr("class", "noactive");
    $("#mainnav a[href='/" + firstFolder + "/']").parent().attr("class", "active");
});

Upvotes: 3

Related Questions