PHP Page Navigation Optimizing - Setting "active" on nav items - php

I have my nav.php setup with code like this. This is to determine the page and then set both the navigation header and the item as active.
if ($_SERVER['PHP_SELF'] == ''.$path.'/links.php') {
$opslinks = "active";
$nav1_active = "active";
} elseif($_SERVER['PHP_SELF'] == ''.$hpath.'/tunnel_status.php') {
$tunnelstatus = "active";
$nav2_active = "active";
$refresh = "<meta http-equiv=\"refresh\" content=\"240\"/>";
} elseif($_SERVER['PHP_SELF'] == ''.$hpath.'/qcall_status.php') {
$qcallstatus = "active";
$nav2_active = "active";
} elseif ($_SERVER['PHP_SELF'] == ''.$path.'/checklist.php') {
$opsdash = "active";
$nav1_active = "active";
} elseif ($_SERVER['PHP_SELF'] == ''.$path.'/index.php') {
$opsindex = "active";
$nav1_active = "active";
} elseif ($_SERVER['PHP_SELF'] == ''.$path.'/tasks_closed.php') {
$optaskclosed = "active";
$nav1_active = "active";
}
I then have the following html code.
<div class="menu-submenu">
<div class="menu-item <?=$opsindex ?? '';?>">
<div class="menu-text">Home</div>
</div>
<div class="menu-item <?=$opsdash ?? '';?>">
<div class="menu-text">Checklist</div>
</div>
<div class="menu-item <?=$opsoutages ?? '';?>">
<div class="menu-text">Outage Management</div>
</div>
<div class="menu-item <?=$opsissues ?? '';?>">
<div class="menu-text">Task List / Issues</div>
</div>
<div class="menu-item <?=$optaskclosed ?? '';?>">
<div class="menu-text">Task List (Closed)</div>
</div>
<div class="menu-item <?=$opslinks ?? '';?>">
<div class="menu-text">Common Links</div>
</div>
</div>
How can I optimize this as I feel this is horribly done and outdated. I've been working on cleaning up all my older code and this is one area I'm not sure about. I know I could technically add the code into the html block itself, but it's not really any better that way.
I also realize the php code block only partially matches what I posted. I have dozens of links, so to condense the info and present enough, I truncated it down.
I'm also working on revamping my PATH variables to be constants and defined in a single file, its sort of a mess at the moment. :)

Using the approach outlined by #CBroe comment above
// set up an array on the php side with a mapping to then loop over to create the nav elements
// the skeleton code below should work with some modifications
$nav_options = [
['page_link' => 'links.php', 'link_text' => 'Common Links' ],
[],
...
]
$arr = [];
foreach( $nav_options as $key => $nav_opt ) {
$url = $path . '/' . $nav_opt["page_link"];
if( $_SERVER['PHP_SELF'] == $url ){
// active
$arr[$key]['css_class'] = 'active';
$arr[$key]['link_href'] = $url;
$arr[$key]['link_text'] = $nav_opt['link_text'];
} else {
// not active
$arr[$key]['css_class'] = '';
$arr[$key]['link_href'] = $url;
$arr[$key]['link_text'] = $nav_opt['link_text'];
}
}
// Then loop over $arr on the html side to produce the nav div elements

Related

.active class via PHP

I created this PHP function:
function active_class($page){
global $pagebase;
if($pagebase == $page){
return "active";
}
elseif($pagebase == null){
$page = "home";
return "active";
}
else{
return "";
}
}
But when I use it with this list:
<ul class="nav navbar-nav">
<li class="<?php echo active_class("home"); ?>">Home</li>
<li class="<?php echo active_class("about"); ?>">About</li>
</ul>
It shows the active class on both at http://example.com without the /home or /about. I am looking for a way to fix this. Any ideas?
$pagebase is just the $_GET['page']. It is the /home or /about for each page.
When $pagebase is null, for it to make just the home tab active, you have to add in - $page == "home" - condition so that the null state is just for the home tab and only returns active once.
Try:
function active_class($page){
global $pagebase;
if($pagebase == $page){
return "active";
}
elseif($pagebase == null && $page == "home" ){
$page = "home";
return "active";
}
else{
return "";
}
}
Another alternative:
<ul class="nav navbar-nav">
<li class="<?php echo ($pagebase=="home"?"active":""); ?>">Home</li>
<li class="<?php echo ($pagebase=="about"?"active":""); ?>">About</li>
</ul>
<li class="<?php echo ($pagebase == 'home')?'active':'';; ?>">Home</li>
I am sure it will work like this way.
After looking back at my code, I figured that I can just change $pagebase to equal home if it is null (No $_GET['page']. This would allow me to use my code meanwhile not using the elseif. Thank you for the replies.

menu tab not becoming active in codeigniter

Here the menu tabs are not becoming and don't know why it seems look like this.Here is the control please have a look
public function vehicle($id=NULL)
{
if (!empty($id)) {
$data['active'] = 2;
$this->Vehicle_model->_table_name = "tbl_vehicles"; //table name
$this->Vehicle_model->_order_by = "id";
$data['vehicle_info'] = $this->Vehicle_model->get_by(array('id' => $id), TRUE);
} else {
$data['active'] = 1;
}
$data['all_vehicle_info'] = $this->Vehicle_model->view_vehicle(null,null);
$this->load->view('admin/vehicle/add_vehicle',$data);
}
here is the view
<ul class="tabs rs-tab">
<li class="<?php echo ($active == 1) ? "active" : ""; ?> tab col s3 "><a href="#manage" >All Vehicles</a></li>
<li class="<?php echo ($active == 2) ? "active" : ""; ?> tab col s3"><a href="#create" >New Vehicles</a></li>
</ul>
<div class="<?php echo ($active == 1) ? "active" : ""; ?>" id="manage" >
</div>
<div class="<?php echo ($active == 2) ? "active" : ""; ?>" id="create">
</div>

Link to blank page and addition new condition in php code

I'd like to add condition to my code so that after click on label it link me to other page. Now this code link to other article on the website. So I guess what should I add to get from my label to other page.
Thank you for answers!
My code is below:
<ul class="nav nav-tabs aboutUsTabs nav-justified" role="tablist">
<?php foreach ($this->items as $key=>$item ){
if($item['children']){ ?>
<li role="presentation" class="<?php if($item['menu']->id==$this->pageId || $item['menu']->id==$this->parentId){ echo 'active'; } ?>"><?php echo $item['menu']->title;?></li>
<?php }else{ ?>
<li role="presentation" class="<?php if($item['menu']->id==$this->pageId || $item['menu']->id==$this->parentId){ echo 'active'; } ?>"><?php echo $item['menu']->title;?></li>
<?php } ?>
<?php } ?>
</ul>
All this start/stop of PHP code hurts my eyes! Anyways, linking to other pages is done with tags. Not quite sure I understand your question, but you could (if you mean labels for form elements) do something like this;
<label for=""> Something Meaningful </label>
I'm sorry, but I took the liberty to clean up your code a little. Hopefully this will make it more readable;
<ul class="nav nav-tabs aboutUsTabs nav-justified" role="tablist">
<?php
foreach ($this->items as $key=>$item ){
$active = NULL;
if($item['menu']->id==$this->pageId || $item['menu']->id==$this->parentId){
$active = 'active';
}
$menu = NULL;
if($item['menu']->id==$this->pageId || $item['menu']->id==$this->parentId){
$menu = 'active';
}
if($item['children']){
echo'<li role="presentation" class="'.$active.'">
'.$item['menu']->title.'
</li>';
}else{
echo'<li role="presentation" class="'.$menu.'">
'.$item['menu']->title.'
</li>';
}
}
?>
</ul>
For your comment question, if you know what item needs a different value, it could be the title f.ex. then you can check against that value and change the output of your element. Maybe something like;
if($item['children']){
if($item['title'] == 'Unique Identifier for your element') {
// In here you could manipulate the output of that one item you want to exclude/change
} else {
// Your normal output
echo'<li role="presentation" class="'.$active.'">
'.$item['menu']->title.'
</li>';
}else{ ... }
And even better would be to perform the check beforehand, so maybe something like;
$link = '#about-us-page-'.$item['menu']->id;
if($item['title'] == "That identifier") {
$link = 'somethingElse';
}
and then change the value of your href tag to;
'.$item['menu']->title.'

creating class active dynamically in php

I am creating a menu dynamically based on the categories registered on the dataBase, What I need is:
When someone click in the link, this option should have the css class 'active', showing in with page the user is and even the pages are created dynamically.
I have no idea how to do this because I am php student and I couldn't find this information in google for "Dynamically menus" Thank you very much.
<nav class="menu">
<ul class="list">
<li class="line"><a id="item" href="index.php">Home</a></li>
<?php
$categories = $db->select("select * from tbl_category");
if($categories){
while ($result = $categories->fetch_assoc()){
echo <<<HTML
<li id="line" ><a class="item" href="categories.php?category=$result[id]">$result[name]</a></li>
HTML;
}
}
?>
</ul>
<nav>
First of all, you're looping through that while loop and adding the id of "line" to each and every <li> element. I suggest you create unique id's for each list item. I don't necessary advocate using the code the way you have it, just as an example, here's your code edited to do just that:
if($categories){
$i = 1;
while ($result = $categories->fetch_assoc()){
$i++;
echo <<<HTML
<li id="line$i" ><a class="item" href="categories.php?category=$result[id]">$result[name]</a></li>
HTML;
}
}
Then when someone clicks on your link, just use jQuery with something like this:
$(".item").click(function() {
$(this).parent('li').addClass('active');
});
Try something like that:
<nav class="menu">
<ul class="list">
<li class="line"><a id="item" href="index.php">Home</a></li>
<?php
$current_page = isset($_GET['category']) ? $_GET['category']: -1;
$categories = $db->select("select * from tbl_category");
if($categories){
while ($result = $categories->fetch_assoc()){
echo '<li id="line">';
if($result['category'] === $current_page) {
// If we're currently in the active page then add the active class to the <a>
echo '<a class="item active" href="categories.php?category='. $result[id] .'">';
} else {
echo '<a class="item" href="categories.php?category='. $result[id] .'">';
}
echo $result['name'];
echo '</a>';
echo '</li>';
}
}
?>
</ul>
<nav>
Thank you all for help, based on your code, I solved doing this:
menu.php:
<nav class="menu" id="menu">
<ul id="list" class="list">
<li id="line" class="<?php if($presentPage == '0')echo 'active';?>"><a id="item" class="item" href="index.php">Home</a></li>
<?php
function checked($pp, $id){
if($pp == $id){
$status = 'active';
return $status;
}
}
$query = "select * from tbl_category";
$category = $db->select($query);
if($category){
while ($result = $category->fetch_assoc()){
echo "
<li id='line' class='".checked($presentPage, $result['id'])."'><a id='item' class='item' href='categories.php?category=".$result['id']."'>".$result['name']."</a></li>
";//end echo
}//end while
}//end if
?>
</ul>
</nav>
In my index.php:
<?php $presentPage = 0;?>
<?php require_once 'header.php';?>
<?php require_once 'menu.php';?>
and in my categories.php:
<?php
if (!isset($_GET['category']) || $_GET['category'] == NULL) {
$presentPage = 0;
}else{
$presentPage = intval($_GET['category']);//just to make sure that the variable is a number
}
?>
<?php require_once 'header.php';?>
<?php require_once 'menu.php';?>
///...my code...
and in my CSS of course:
.active{
background: linear-gradient(#821e82, #be5abe);
}
Thats is working perfectly for me, Thank for all help.

How add class='active' to html menu with php

I want to put my html navigation in a separate php file so when I need to edit it, I only have to edit it once. The problem starts when I want to add the class active to the active page.
I've got three pages and one common file.
common.php :
<?php
$nav = <<<EOD
<div id="nav">
<ul>
<li><a <? if($page == 'one'): ?> class="active"<? endif ?> href="index.php">Tab1</a>/</li>
<li>Tab2</li>
<li>Tab3</li>
</ul>
</div>
EOD;
?>
index.php :
All three pages are identical except their $page is different on each page.
<?php
$page = 'one';
require_once('common.php');
?>
<html>
<head></head>
<body>
<?php echo $nav; ?>
</body>
</html>
This simply won't work unless I put my nav on each page, but then the whole purpose of separating the nav from all pages is ruined.
Is what I want to accomplish even possible? What am I doing wrong?
Thanks
EDIT: When doing this, the php code inside the li don't seem to run, it's just being printed as if it was html
why don't you do it like this:
in the pages:
<html>
<head></head>
<body>
<?php $page = 'one'; include('navigation.php'); ?>
</body>
</html>
in the navigation.php
<div id="nav">
<ul>
<li>
<a <?php echo ($page == 'one') ? "class='active'" : ""; ?>
href="index1.php">Tab1</a>/</li>
<li>
<a <?php echo ($page == 'two') ? "class='active'" : ""; ?>
href="index2.php">Tab2</a>/</li>
<li>
<a <?php echo ($page == 'three') ? "class='active'" : ""; ?>
href="index3.php">Tab3</a>/</li>
</ul>
</div>
You will actually be able to control where in the page you are putting the navigation and what parameters you are passing to it.
Later edit: fixed syntax error.
A very easy solution to this problem is to do this.
<ul>
<li class="<?php if(basename($_SERVER['SCRIPT_NAME']) == 'index.php'){echo 'current'; }else { echo ''; } ?>">Home</li>
<li class="<?php if(basename($_SERVER['SCRIPT_NAME']) == 'portfolio.php'){echo 'current'; }else { echo ''; } ?>">Portfolio</li>
<li class="<?php if(basename($_SERVER['SCRIPT_NAME']) == 'services.php'){echo 'current'; }else { echo ''; } ?>">Services</li>
<li class="<?php if(basename($_SERVER['SCRIPT_NAME']) == 'contact.php'){echo 'current'; }else { echo ''; } ?>">Contact</li>
<li class="<?php if(basename($_SERVER['SCRIPT_NAME']) == 'links.php'){echo 'current'; }else { echo ''; } ?>">Links</li>
</ul>
Which will output
<ul>
<li class="current">Home</li>
<li class="">Portfolio</li>
<li class="">Services</li>
<li class="">Contact</li>
<li class="">Links</li>
</ul>
Your index.php code is correct. I am including the updated code for common.php below then I will explain the differences.
<?php
$class = ($page == 'one') ? 'class="active"' : '';
$nav = <<<EOD
<div id="nav">
<ul>
<li><a $class href="index.php">Tab1</a>/</li>
<li>Tab2</li>
<li>Tab3</li>
</ul>
</div>
EOD;
?>
The first issue is that you need to make sure that the end declaration for your heredoc -- EOD; -- is not indented at all. If it is indented, then you will get errors.
As for your issue with the PHP code not running within the heredoc statement, that is because you are looking at it wrong. Using a heredoc statement is not the same as closing the PHP tags. As such, you do not need to try reopening them. That will do nothing for you. The way the heredoc syntax works is that everything between the opening and closing is displayed exactly as written with the exception of variables. Those are replaced with the associated value. I removed your logic from the heredoc and used a tertiary function to determine the class to make this easier to see (though I don't believe any logical statements will work within the heredoc anyway)
To understand the heredoc syntax, it is the same as including it within double quotes ("), but without the need for escaping. So your code could also be written like this:
<?php
$class = ($page == 'one') ? 'class="active"' : '';
$nav = "<div id=\"nav\">
<ul>
<li><a $class href=\"index.php\">Tab1</a>/</li>
<li>Tab2</li>
<li>Tab3</li>
</ul>
</div>";
?>
It will do exactly the same thing, just is written somewhat differently. Another difference between heredoc and the string is that you can escape out of the string in the middle where you can't in the heredoc. Using this logic, you can produce the following code:
<?php
$nav = "<div id=\"nav\">
<ul>
<li><a ".(($page == 'one') ? 'class="active"' : '')." href=\"index.php\">Tab1</a>/</li>
<li>Tab2</li>
<li>Tab3</li>
</ul>
</div>";
?>
Then you can include the logic directly in the string like you originally intended.
Whichever method you choose makes very little (if any) difference in the performance of the script. It mostly boils down to preference. Either way, you need to make sure you understand how each works.
I think you need to put your $page = 'one'; above the require_once.. otherwise I don't understand the question.
Why don't you create a function or class for this navigation and put there active page as a parameter? This way you'd call it as, for example:
$navigation = new Navigation( 1 );
or
$navigation = navigation( 1 );
I know this is old, but none of these answers are very good (sry ppl)
The BEST way to do it (without writing out convoluted classes) is to compare the current $_SERVER['REQUEST_URI'] to the href of the link. You're almost there.
Try this. (Taken from http://ma.tt/scripts/intellimenu/)
$nav = <<<EOD
<div id="nav">
<ul>
<li>Tab1</li>
<li>Tab2</li>
<li>Tab3</li>
</ul>
</div>
EOD;
$lines = explode("\n", $nav);
foreach($lines as $line)
{
if(preg_match('/href="([^"]+)"/', $line, $url)) {
if(substr($_SERVER['REQUEST_URI'], 0, 5) == substr($url[1], 0, 5)) {
$line = str_replace('><a', ' class="current-menu-item"><a', $line);
}
}
echo $line . "\n";
}
$page='one' should occur before you require_once() not after. After is too late- the code has already been required, and $nav has already been defined.
You should use include('header.php'); and include('footer.php'); instead of setting a $nav variable early on. That increases flexibility.
Make more functions. Something like this really makes things easier to follow:
function maybe($x,$y){return $x?$y:'';}
function aclass($k){return " class=\"$k\" "; }
then you can write your "condition" like this:
<a href="..." <?= maybe($page=='one',aclass('active')) ?>> ....
You could use this PHP, hope it helps.
<?php if(basename($_SERVER['PHP_SELF'], '.php') == 'home' ) { ?> class="active" <?php } else { ?> <?php }?>
So a list would be like the below.
<ul>
<li <?php if( basename($_SERVER['PHP_SELF'], '.php') == 'home' ) { ?> class="active" <?php } else { ?> <?php }?>><i class="fa fa-dashboard"></i> <span>Home</span></li>
<li <?php if( basename($_SERVER['PHP_SELF'], '.php') == 'listings' ) { ?> class="active" <?php } else { ?> <?php }?>><i class="fa fa-th-list"></i> <span>Other</span></li>
</ul>
CALL common.php
<style>
.ddsmoothmenu ul li{float: left; padding: 0 20px;}
.ddsmoothmenu ul li a{display: block;
padding: 40px 15px 20px 15px;
color: #4b4b4b;
font-size: 13px;
font-family: 'Open Sans', Arial, sans-serif;
text-align: right;
text-transform: uppercase;
margin-left: 1px; color: #fff; background: #000;}
.current .test{ background: #2767A3; color: #fff;}
</style>
<div class="span8 ddsmoothmenu">
<!-- // Dropdown Menu // -->
<ul id="dropdown-menu" class="fixed">
<li class="<?php if(basename($_SERVER['SCRIPT_NAME']) == 'index.php'){echo 'current'; }else { echo ''; } ?>">Home <i>::</i> <span>welcome</span></li>
<li class="<?php if(basename($_SERVER['SCRIPT_NAME']) == 'about.php'){echo 'current'; }else { echo ''; } ?>">About us <i>::</i> <span>Who we are</span></li>
<li class="<?php if(basename($_SERVER['SCRIPT_NAME']) == 'course.php'){echo 'current'; }else { echo ''; } ?>">Our Courses <i>::</i> <span>What we do</span></li>
</ul><!-- end #dropdown-menu -->
</div><!-- end .span8 -->
add each page
<?php include('common.php'); ?>
<ul>
<li><a <?php echo ($page == "yourfilename") ? "class='active'" : ""; ?> href="user.php" ><span>Article</span></a></li>
<li><a <?php echo ($page == "yourfilename") ? "class='active'" : ""; ?> href="newarticle.php"><span>New Articles</span></a></li>
</ul>
The solution i'm using is as follows and allows you to set the active class per php page.
Give each of your menu items a unique class, i use .nav-x (nav-about, here).
<li class="nav-item nav-about">
<a class="nav-link" href="about.php">About</a>
</li>
At the top of each page (about.php here):
<!-- Navbar Active Class -->
<?php $activeClass = '.nav-about > a'; ?>
Elsewhere (header.php / index.php):
<style>
<?php echo $activeClass; ?> {
color: #fff !important;
}
</style>
Simply change the .nav-about > a per page, .nav-forum > a, for example.
If you want different styling (colors etc) for each nav item, just attach the inline styling to that page instead of the index / header page.
seperate your page from nav bar.
pageOne.php:
$page="one";
include("navigation.php");
navigation.php
if($page=="one"){$oneIsActive = 'class="active"';}else{ $oneIsActive=""; }
if($page=="two"){$twoIsActive = 'class="active"';}else{ $twoIsActive=""; }
if($page=="three"){$threeIsActive = 'class="active"';}else{ $threeIsActive=""; }
<ul class="nav">
<li <?php echo $oneIsActive; ?>>One</li>
<li <?php echo $twoIsActive; ?>><a href="#">Page 2</li>
<li <?php echo $threeIsActive; ?>><a href="#">Page 3</li>
</ul>
I found that I could also set the title of my pages with this method as well.
$page="one";
$title="This is page one."
include("navigation.php");
and just grab the $title var and put it in between the "title" tags. Though I am sending it to my header page above my nav bar.
<a href="store/index" <?php if($_SERVER['REQUEST_URI'] == '/store/index') { ?>class="active"<?php } ?> > Link </a>
<a href="account/referral" <?php if($_SERVER['REQUEST_URI'] == '/account/referral') { ?>class="active"<?php } ?> > Link </a>
PHP code
<?php
function activeClass($chkStr){
// echo "testing data";
// echo strlen($_SERVER['REQUEST_URI']);
if($chkStr=="home" && strlen($_SERVER['REQUEST_URI'])<3){
return "active";
}
if (stripos($_SERVER['REQUEST_URI'], $chkStr)!==false){
return "active";
}
else{
return "";
}
}
?>
HTML CODE :
<ul class="navbar-nav">
<li class="nav-item <?php echo activeClass("home"); ?>">
<a class="nav-link txt" href="/">Home <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item <?php echo activeClass("about-us.php"); ?>">
<a class="nav-link txt" href="about-us.php">About Us</a>
</li>
<li class="nav-item <?php echo activeClass("services.php"); ?>">
<a class="nav-link txt" href="services.php">Services</a>
</li>
<li class="nav-item <?php echo activeClass("our-team.php"); ?>">
<a class="nav-link txt" href="our-team.php">Our team</a>
</li>
<li class="nav-item <?php echo activeClass("media-awards.php"); ?>">
<a class="nav-link txt" href="media-awards.php">Media & Awards</a>
</li>
<li class="nav-item <?php echo activeClass("blog.php"); ?>">
<a class="nav-link txt" href="blog.php">Blog</a>
</li>
<li class="nav-item <?php echo activeClass("contact-us.php"); ?>">
<a class="nav-link txt" href="contact-us.php">Contact Us</a>
</li>
</ul>

Categories