Add class="active" to active page using PHP

javascript add class
add class in css
remove class javascript
button click add class
javascript add class to body
how to add class to html
javascript add class to html
inline javascript add class
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>

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];
?>

How To Add a Class Name, Add a class name to the div element with id="myDIV" (in this example we use a button to add the class). Example. <button onclick="myFunction()">Try it<  Well organized and easy to understand Web building tutorials with lots of examples of how to use HTML, CSS, JavaScript, SQL, PHP, Python, Bootstrap, Java and XML.

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>
...

jQuery addClass() Method, Tip: To add more than one class, separate the class names with spaces. Syntax. $(selector).addClass(classname,function(index,currentclass)). Parameter  A function returning one or more space-separated classes or an array of classes to be added to the existing class name(s). Receives the index position of the element in the set and the existing class name(s) as arguments. Within the function, this refers to the current element in the set.

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>

How To Add a Class Name, Add a class name to the div element with id="myDIV" (in this example we use a button to add the class). Example. <button onclick="myFunction()">Try it<  The addClass() method adds one or more class names to the selected elements. This method does not remove existing class attributes, it only adds one or more class names to the class attribute. Tip: To add more than one class, separate the class names with spaces.

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");
});

Element.classList, The addClass is an inbuilt method in jQuery which is used to add more property to each selected element. It can also be used to change the property of the  If you were on a waitlist and received an Add Code, see the instructions for “Adding a Class with an Add Code” in the MyPortal Registration Guide. Waitlisted students get first consideration for available seats in classes, but it is still possible for other students to try to add courses once school begins.

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 />';
}

jQuery, Add Class. Adds class(es) to elements while animating all style changes. Examples. Effect demo · addClass demo · Animate demo  Adding a class in the Online Student Center is simple! 1. Log in to the Online Student Center at My.maricopa.edu with your MEID and password. 2. Click the Add a Class link under the Academics heading and Enrollment sub-heading. 3. Select the college and term that you want to register for, and click Continue.

Add Class, addClass( className [, options ] ). className. Type: String. One or more class names (space separated) to be added to the class attribute of each  Create a new class. From the Project menu, click Add Class. In the Add New Item dialog box, for Class name type BaseballTeam, and then click Open. Note In Visual C# 2005, Open is changed to Add. Examine the code for the new class in the Code View window. Define fields and constructors. From the View menu, click Class View. In the Class View

.addClass(), If you're only targeting modern browsers: Use element.classList.add to add a class: element.classList.add("my-class");. And element.classList.remove to remove  FREE On-Demand Webinar Series Break Through the Cycle of Procrastination and Overwhelm Lynne Edris - Procrastination is one of the most debilitating challenges caused by our ADD / ADHD, creating stress, lost productivity, and costing us our self-esteem and our reputations.

How do I add a class to a given element?, Class and Style Bindings. A common need for data binding is manipulating an element's class list and its inline styles. Then add some classes when using it: Add students to a class team you've already created. You'll also be able to choose if they should receive past assignments in the class. If you're having trouble adding students to your class, check with your IT Admin to make sure you have the right permissions.

Comments
  • Is the part you need to be active always the first segment?
  • if you want flexible code, you have to add your real URL after translate via rewrite code. however i suggest to make it using javascript or jquery.
  • No, It all depends on what directory im in, regardless if how many layers of dirrectories i am in deep, i just want it to look for what dirrectory im in (first layer)
  • Worked for me.but PHP code can be modified with this $first_part = basename($_SERVER['PHP_SELF'], ".php");
  • @RickCalder I disagree, your answer is better.
  • Everything works here, besides the url dirrectory being recognized and applied to the code...but the whole, active, noactive class establishing works. Im just not sure why it isn't recognizing directory
  • @AlexSarnowski are you saying that $directory = explode('/',ltrim($_SERVER['REQUEST_URI'],'/')); is not working? ie on http://example.com/tutorials/css/flawless-dropdown-menu that $directory != tutorials? Could you echo $directory to see what it is set to, compared to the directory you are in? Could it a case-sensitive issue?
  • I tried to echo it out and it says "Notice : Array to string conversion in "
  • And yes, i'm saying when i'm on example.com/tutorials/css/flawless-dropdown-menu , all of the <li> are class="noactive" , when tutorials should be class="active"
  • won't this affect all <li> on the page?
  • Of course, but as Alex Sarnowski has not set any id on his ul and this is only demo code, I think it's okay to do so ;)
  • how could i possibly change it if , id="mainnav"....that was foolish of me to not set an id.
  • @AlexSarnowski I changed it for you.