//ads:
?>
Add Class in html Dynamically in PHP
PHP Snippet 1:
<?php
$thisPage = "home";
?>
<html>
<head>
...
...
<body>
<ul class="nav pull-right">
<li <?php if($thisPage == "home") echo 'class="active"'; ?>>
<a href="index.php"><i class="icon-home"></i><br />Home</a>
</li>
<li>
<a href="portfolio.html"><i class="icon-camera"></i><br />Portfolio</a>
</li>
PHP Snippet 2:
<?php
$urlArr = explode("/", $_SERVER['REQUEST_URI']);
$active_class = array_pop($urlArr); ?>
<ul class="nav pull-right">
<li class="<?php echo ($active_class == "index.php") ? "active" : ""; ?>">
<a href="index.php"><i class="icon-home"></i><br />Home</a>
</li>
<li class="<?php echo ($active_class == "portfolio.html") ? "active" : ""; ?>">
<a href="portfolio.html"><i class="icon-camera"></i><br />Portfolio</a>
</li>
</ul>
PHP Snippet 3:
//First, get the current URL
var url = window.location.href; //output: http://example.org/portfolio.html
//Then split them to array by '/'
var arrurl = url.split('/'); //output: Array [ "http:", "", "example.org", "portfolio.html" ]
//Get last portion of the uri
var lasturi = arrurl[arrurl.length-1]; //output: portfolio.html
//Split the last segment by '.'
var arruri = lasturi.split('.'); //output: Array [ "portfolio", "html" ]
//Get the first value of previous array
var page = arruri[0]; //output: portfolio
PHP Snippet 4:
//Iterate to navbar
$('#mynavbar a').each(function () {
//Get attribute href value
var href = $(this).attr("href");
//Split by '.' to array
var arrhref = href.split('.');
//Get the first portion
var hrefportion = arrhref[0];
//Now, we should add class 'active' to the href (also parent li element)
//if the 'hrefportion' is equal to 'page' in this case 'portfolio'
if (hrefportion == page) {
//Add 'active class to the anchor
$(this).addClass("active");
//also its parent li element
var li = $(this).parent();
li.addClass("active");
}
});