I have this code in header.php:
<?php
$page = "";
?>
<ul class="nav navbar-nav navbar-right nav-pos">
<li <?php if ($page == "home") { ?> class="active"<?php } ?>>Home</li>
<li <?php if($page == 'about') { ?> class="active"<?php } ?>>About us</li>
<li <?php if($page == 'contact'){ ?> class="active"<?php } ?>>Contact us</li>
<li class="hidden-xs"><i class="fa fa-search fa-rotate-90"></i></li>
</ul>
and on every page i put this code(and the name change depends on current page):
<?php include 'header.php';
$page = 'about' ?>
and in css i made this:
.active{color:red }
But it is not working... any idea why?
Thank you for time, I really appreciate it
The problem is that in your header.php you explicitly set $page = "" - which means none of the checks for $page == 'about'(etc) are passing.
Although you do set $page = 'about' in your main script, this is after the code in header.php has run, and its html output produced.
The solution is simple:
1) remove the $page = "" from header.php
2) set $page = "about" (or equivalent) before the include
You can do by using jQuery just adding this script in the footer section.
$(document).ready(function() {
// get current URL path and assign 'active' class
var pathname = window.location.pathname;
$('.nav > li > a[href="'+pathname+'"]').parent().addClass('active');
});
In your case, this will work.
$(function(){
var current = location.pathname;
$('.nav li a').each(function(){
var $this = $(this);
// if the current path is like this link, make it active
if($this.attr('href').indexOf(current) !== -1){
$this.addClass('active');
}
})
});
first you should remove $page = ""; from header
<?php
$page = "";//remove this line in header file
?>
<ul class="nav navbar-nav navbar-right nav-pos">
Second in every page swap these two lines
<?php
$page = 'about';//swap these lines
include 'header.php' ;
?>
some details: when header load then $page is empty and your conditions false in li tag. so, before header load you should assign value to $page
the best way: you should used $_SERVER['REQUEST_URI'] instead of hard coded $page. Example:
$url= explode('/',$_SERVER['REQUEST_URI']);
$page = end($request_array);//this show your_page.php
$page=preg_replace('"\.php$"', '', $page )//this will remove .php extension
Related
I am trying to highlight currently open menu item using PHP.
HTML for my menu items.
<ul class="menu">
<li>Edit Profile</li>
<li>Edit Contact</li>
<li>Edit Facilities</li>
<li>Edit Location</li>
<li>Manage Images</li>
</ul>
This is how I tried it in PHP:
if ($_SERVER['QUERY_STRING']) {
list($queryString) = explode('&',$_SERVER['QUERY_STRING']);
$openPage = $queryString;
list($key, $value) = explode('=',$openPage);
$currentPage = $value;
// Determine what menu item to be highlight:
switch ($currentPage) {
case 'edit-profile':
$class1 = 'class="active"';
break;
case 'edit-contact':
$class2 = 'class="active"';
break;
case 'edit-facilities':
$class3 = 'class="active"';
-----------
// Default is to include the main page.
default:
$class = 'class=""';
break;
} // End of main switch.
} else {
//Determine The Index page
$path = $_SERVER['PHP_SELF'];
$indexPage = basename($path);
$indexPage = basename($path, '.php');
}
This is how I echo these classes in my menus:
<li <?php if(isset($class1)) echo $class1; ?>>Edit Profile</li>
<li <?php if(isset($class2)) echo $class2; ?>>Edit Contact</li>
This is solution is working for me. But my problem is, if I have lot of pages I need to use many class variables in SWITCH case.
Can anybody tell me is there alternative solution for this to minimize my PHP code?
Hope somebody may help me out.
Thank you.
One simple solution would be to store the menu items in a map, and iterate over them:
$menuItems = [
'edit-profile' => [
'url' => 'index.php?p=edit-profile&error=message',
'name' => 'Edit Profile'
],
'edit-contact' => [
'url' => 'index.php?p=edit-contact',
'name' => 'Edit Contacts'
],
...
]
Then iterate over the items.
<ul class="menu">
<?php
foreach($menuItems as $menuItem => $desc) {
// You get $currentPage from the query string
$class = ($currentPage === $menuItem)? 'class="active"': '';
echo '<li '.$class.'>'.$desc['name'].'</li>';
}
?>
</ul>
With this you don't need SWITCH case.
<li <?php if($currentPage=='edit-profile') echo 'class="active"'; ?>>Edit Profile</li>
<li <?php if($currentPage=='edit-contact') echo 'class="active"'; ?>>Edit Contact</li>
You can use array and try like this
if ($_SERVER['QUERY_STRING']) {
list($queryString) = explode('&',$_SERVER['QUERY_STRING']);
$openPage = $queryString;
list($key, $value) = explode('=',$openPage);
$currentPage = $value;
// Determine what menu item to be highlight:
// Store in array, you will be having only one item in array
$class[$currentPage] = 'class="active"';
} else {
//Determine The Index page
$path = $_SERVER['PHP_SELF'];
$indexPage = basename($path);
$indexPage = basename($path, '.php');
}
and the menu can be
<li <?php if(isset($class['edit-profile'])) echo $class['edit-profile']; ?>>Edit Profile</li>
<li <?php if(isset($class['edit-contact'])) echo $class['edit-contact']; ?>>Edit Contact</li>
Note: this not tested, as I have no access to PHP right now.
Rather than doing all this, just take all your menu items in an array and loop over it.
You are sending page parameter with variable.
So, instead have a control over it while sending itself.
Array of page will have page title as key and page url as value.
This way, you do not need separate variables, single variable in loop will serve the job.
<?php
$pages = array(); // Get all page titles and urls in array.
$pages['Edit Profile'] = 'edit-profile&error=message';
$pages['Edit Contact'] = 'edit-contact';
$pages['Edit Facilities'] = 'edit-facilities';
$pages['Edit Location'] = 'edit-location';
$pages['Manage Images'] = 'edit-images';
if (! empty($pages)) {
$current = (isset($_GET['p'])) ? $_GET['p'] : '';
?>
<ul>
<?php
foreach ($pages as $title => $url) {
$active = ($current == $url) ? 'active' : '';
?>
<li><?php echo $title;?></li>
<?php
}
?>
</ul>
<?php
}
?>
Use PHP to generate your own menu structure but for highlighting we can use Jquery.
See example below:
<style>
.active{ background-color:#3F6}
</style>
<ul class="menu">
<li>Home</li>
<li>Edit Profile</li>
<li>Edit Contact</li>
<li>Edit Facilities</li>
<li>Edit Location</li>
<li>Manage Images</li>
</ul>
<script type='text/javascript' src='//code.jquery.com/jquery-1.11.0.js'></script>
<script>
var aurl = window.location.href; // Get the absolute url
$('.menu li a').filter(function() {
return $(this).prop('href') === aurl;
}).parent('li').addClass('active');
</script>
I just want to add a css class named "active" to my navigation links when its page opened using php.
In my website the content have broken into its individual components. And those components are separated, organized, and put back together using one index file. (website bootstrap file) Actually I am modularizing this website using php.
My Navigation is something similar to this code -
...
<li>
Dashboard
</li>
<li>
Page Two
</li>
<li>
Page Page Three
</li>
...
This is how my index.php looks like -
// Validate what page to show:
if (isset($_GET['p'])) {
$p = $_GET['p'];
} elseif (isset($_POST['p'])) { // Forms
$p = $_POST['p'];
} else {
$p = NULL;
}
// Determine what page to display:
switch ($p) {
case 'dashboard':
$page = 'dashboard.inc.php';
$page_title = 'Control Panel';
break;
case 'page-three':
$page = 'page-three.inc.php';
$page_title = 'Page Three';
break;
case 'page-two':
$page = 'page-two.inc.php';
$page_title = 'Page Two';
break;
// Default is to include the main page.
default:
$page = 'login.inc.php';
$page_title = 'Control Panel Login';
break;
} // End of main switch.
// Make sure the file exists:
if (!file_exists('./modules/' . $page)) {
$page = 'login.inc.php';
$page_title = 'Control Panel Login';
}
include('./includes/header.html');
include('./modules/' . $page);
include('./includes/footer.html');
I have no idea how to add active css class dynamically to my links. hope somebody may help me out.
Thank you.
Compare the current file with the page to load using $_SERVER['PHP_SELF'].
If they are equal:
case 'dashboard':
$page = 'dashboard.inc.php';
$page_title = 'Control Panel';
$class == ($page == $p) ? 'active' : '';
break;
And add this class to HTML.
<li class="<?php echo $class;?>">
...
if You are ok with JS/Jquery solution here it is
HTML CODE:
<ul class="menu">
<li>
Dashboard
</li>
<li>
Page Two
</li>
<li>
Page Page Three
</li>
</ul>
JS Code:
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
$(document).ready(function(){
var PageName = getParameterByName('p');
$("li a[href*='"+PageName+"']").addClass("active");
});
Working example is here
http://jsfiddle.net/naveenkumarpg/f16yqrpx/3/
I have an include file that includes the header and footer of my site. But in the header I use an active class to let the menu-item change when on that page. How can you achieve this using one include file? With PHP?
I found this:
index.php
<?php $page == 'one'; include('includes/header.php'); ?>
header.php
<li>
<a <?php echo ($page == 'one') ? "class='active'" : ""; ?>
href="contact.php">Contact</a>/</li>
But it's not changing, when I just used the class on every page seperately, it worked.
Index.php
<?php $page = 'one'; include('includes/header.php'); ?>
$page = 'one'. "==" is a comparison operator http://www.php.net/manual/en/language.operators.comparison.php
Header.php
<li><a href="#"<?php if($page == 'one'){ echo ' class="active"';}?>>LINK</a></li>
I think is more clean like that
just move the echo to correct place(s), because your syntax is not correct
Like this;
<li>
<a
<?php
echo( $page == 'one' ? "class='active'" : "");
?>
href="contact.php">Contact</a>
/
</li>
And also you should correct this in include.php
$page = 'one';
with single "=" sign
<?php
$page = 'one';
include('includes/header.php');
?>
$page =1; not $page == 1; because it is assignment of a variable.
Rest of the code is fine.
Well, Following is the function which select current page name. ex: index.php, owner.php, contactus.php etc. I created this function because i need to active a css id(#active) selector which highlight the current page.
Function
function curPageName() {
return substr($_SERVER["SCRIPT_NAME"],strrpos($_SERVER["SCRIPT_NAME"],"/")+1);
}
$pagename = curPageName();
And this is my Navigation Code:
<ul>
<li><a href="index.php" <?php if($pagename == "index.php") echo "id='active'";
?>>HOME</a></li>
<li><a href="owner.php" <?php if($pagename == "owner.php") echo "id='active'"; ?>>LIST
YOUR PROPERTY</a></li>
<?php
$menu = mysql_query("SELECT * FROM page where status = 1");
while($re = mysql_fetch_array($menu))
{
$pageid = $re['pageid'];
$pagelink = $re['pagelink'];
$pagename = strtoupper($re['pagename']);
$pagedes = $re['pagedes'];
echo "<li><a href='page.php?pageid=$pageid'>$pagename</a></li>";
}
?>
<li><a href="contactus.php" <?php if($pagename == "contactus.php") echo "id='active'";
?>>CONTACT US</a></li>
</ul>
So, My questions is It's active the css id selector to Index.php and owner.php. BUT It's doesn't active the css selector to contactus.php page.
Is there anything wrong in my code?
You have overwritten $pagename into while loop
while($re = mysql_fetch_array($menu))
{
$pageid = $re['pageid'];
$pagelink = $re['pagelink'];
$pagename = strtoupper($re['pagename']);
^^^^^ overwritten variable value change this variable name
$pagedes = $re['pagedes'];
echo "<li><a href='page.php?pageid=$pageid'>$pagename</a></li>";
}
-------------------------------------vvvvvvvvv- this will be last value of while loop
<li><a href="contactus.php" <?php if($pagename == "contactus.php") echo "id='active'";
?>>CONTACT US</a></li>
I'm so used to writing for Wordpress that I don't know how to do a simple PHP logic statement by itself!
For a very basic project, I'm trying to include an unordered list on the index.php page. Here's an example of code that I am trying to use:
<?php
$index = $_SERVER['REQUEST_URI'];
if ($index == "/") {
?><ul id="links">
<li>Facebook</li>
<li>Example</li>
<li>Test</li>
<li>Page</li>
</ul>
<?php } ?>
I know this needs to work for index pages ending with the actual URI of index.php as well as a blank suffix without index.php. How can I write this code to work correctly?
You need to use basename() function to get actual page name like this:
<?php
$page = basename($_SERVER['REQUEST_URI']);
if ($page == 'index.php' || $page == "/" || $page == '') {
?><ul id="links">
<li>Facebook</li>
<li>Example</li>
<li>Test</li>
<li>Page</li>
</ul>
<?php } ?>
It does work however if you use SCRIPT_NAME with the slashes following.
<?php
$page = basename($_SERVER['SCRIPT_NAME']);
if ($page == 'index.php' || $page == "/" || $page == '')
{ ?>
Hi This should show up.
<?php }?>