I am loading in the following navbar html from a required PHP file:
<ul id="navlist">
<li id="active">Home</li>
<li>About</li>
<li>News</li>
<li>Applying</li>
<li>Current <br />Residents</li>
<li>Alumni</li>
<li>Contact</li>
</ul>
Depending on the page that I am on (let's say I am on the alumni.php page) I want that list item to be given the ID "active"?
Edit: Here is my header.php code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<link rel="stylesheet" href="styles/main.css" type="text/css" media="screen" charset="utf-8"/>
<link rel="stylesheet" href="styles/navbar.css" type="text/css" media="screen" charset="utf-8"/>
<title>some title</title>
</head>
<body>
<div id="header">
<div id="left">
<img src="images/tree.png" alt="tree" width="87" height="98"></img>
</div>
<div id="right">
<
</div>
</div>
<div id="navigation">
<ul id="navlist">
<li>Home</li>
<li>About</li>
<li>News</li>
<li>Applying</li>
<li>Current <br />Residents</li>
<li>Alumni</li>
<li>Contact</li>
</ul>
</div>
I assume that I need to do this through Javascript once the page loads? How would I do this?
as said in comment, PHP will be a better way.
You can simple doing it like this :
<?php
$header = file_get_content('header.html');
$page = 'about.php';
$header = str_replace('<li><a href="'.$page.'">', '<li id="active"><a href="#">', $header);
You should assign the ID (which should be a class, semantically speaking, IMHO) using PHP whilst generating the page. Using JS is not only troublesome (you have to go and check your location, probably match a regexp, etc), but also inelegant.
I'd say that in common coding for javascript where you want a particular element to be 'active' or 'highlighted' or 'enabled', make use of the class attribute. Your id attribute implies a static attribute of the data being used.
I think this will do what you want.
<ul id="navlist">
<li id="home">
Home
</li>
<li id="about">
About
</li>
<li id="news">
News
</li>
<li id="applying">
Applying
</li>
<li id="currentResidents">
Current Residents
</li>
<li id="alumni">
Alumni
</li>
<li id="contact">
Contact
</li>
</ul>
<script type="text/javascript">
var pagePath = window.location.pathname;
var pageName = pagePath.substring(pagePath.lastIndexOf('/') + 1);
var currentActive;
function setActivePage(page)
{
if(currentActive)
document.getElementById(currentActive).removeAttribute("class");
document.getElementById(page).setAttribute("class", "active");
currentActive = page;
}
if(pageName == "about.html")
setActivePage("about");
else if(pageName == "otherpage.html")
setActivePage("otherpage");
// Etc...
</script>
If you were using jQuery this may have been done in a better and lesscode way... but I assume you're not using it.
Hope it helps :)
While it may be possible (I haven't actually tried it), you would not typically change the id of an element in the page. Instead, it would be a better approach to use class="active" instead of id="active".
Also, you probably want to generate the appropriate html for it on the server-side, as you're building the rest of the page. Something like this would work (though there are many different ways to build this code, depending on your server's implementation):
<ul id="navlist">
<li class="<?php echo (($currentPage=='Home')?'active':''); ?>">Home</li>
<li class="<?php echo (($currentPage=='About')?'active':''); ?>">About</li>
<li class="<?php echo (($currentPage=='News')?'active':''); ?>">News</li>
<li class="<?php echo (($currentPage=='Applying')?'active':''); ?>">Applying</li>
<li class="<?php echo (($currentPage=='Residents')?'active':''); ?>">Current <br />Residents</li>
<li class="<?php echo (($currentPage=='Alumni')?'active':''); ?>">Alumni</li>
<li class="<?php echo (($currentPage=='Contact')?'active':''); ?>">Contact</li>
</ul>
Note: I've also removed the id="current" attribute from the anchor (<a ...>), because I'm assuming that this would change depending on the current page as well, and it's unnecessary, because you can build CSS selectors to address the anchor, without giving it its own special id or class.
Here's what your CSS might look like:
#navlist li.active {
/* css rules for the active LI */
}
#navlist li.active a {
/* css rules for the active (a.k.a. "current") anchor inside the active LI */
}
hope this helps.
[edit] As I said above, it all depends on the architecture of your php code. But assuming that you have a bunch of php pages (eg: "Home.php", "About.php", "News.php", etc.); and each of those pages includes your nav code using something like: require("nav.php");. Then you can just do the following in each of your main php files:
<?php
/* $currentPage, declared here, will be available to php code inside nav.php */
$currentPage = strtolower(basename(__FILE__));
require("nav.php");
?>
Just be sure that you set $currentPage, in each page's main script, somewhere prior to including your nav code (ie. before you call require(...)). The nav code will then be able to "see" $currentPage and use it.
So, for example, if the above code is executed in a file called "About.php", then $currentPage will be set to "about.php" (filename gets converted to all lowercase by the call to strtolower(...)). Then, when "nav.php" gets included, it will be able to access $currentPage and "see" that we're on the 'about' page.
You can change my example above, as follows, to use values of $currentPage that were generated from the filename using the approach I've described here.
<ul id="navlist">
<li class="<?php echo (($currentPage=='home.php')?'active':''); ?>">Home</li>
<li class="<?php echo (($currentPage=='about.php')?'active':''); ?>">About</li>
<li class="<?php echo (($currentPage=='news.php')?'active':''); ?>">News</li>
<li class="<?php echo (($currentPage=='applying.php')?'active':''); ?>">Applying</li>
<li class="<?php echo (($currentPage=='residents.php')?'active':''); ?>">Current <br />Residents</li>
<li class="<?php echo (($currentPage=='alumni.php')?'active':''); ?>">Alumni</li>
<li class="<?php echo (($currentPage=='contact.php')?'active':''); ?>">Contact</li>
</ul>
Related
My problem is simple, and I've been trying to think of a way around this for a while. Essentially, I have a free HTML template which I downloaded. The entire template is in html only, meaning if I change something in the header, I have to go through 10 pages and change the HTML code for the header. So my solution was to remove the header html code and put a have another file called header.php and just echo it on all the pages.
However, there is a problem. As you can see, on the first line it says <li class="nav-item active">. There is an active bit. So whatever page we are currently on, we have to put active next to nav-item. Then to further complicate this... If you have a drop down menu, the class= looks difference. If you are on a page which is on a dropdown menu Like this <li class="nav-item submenu dropdown active">
So my question is, how can I detect what page I am on and make sure to put the active bit in the right section?
When we are on index.html
<li class="nav-item active"><a class="nav-link" href="index.html">Home</a></li>
<li class="nav-item"><a class="nav-link" href="about-us.html">About</a></li>
<li class="nav-item submenu dropdown">
<a class="nav-link" href="#">Portfolio</a>
<ul class="dropdown-menu">
<li class="nav-item"><a class="nav-link" href="portfolio.html">Portfolio</a></li>
<li class="nav-item"><a class="nav-link" href="portfolio-det.html">Portrfolio Dets</a>
</ul>
</li>
When we are on portfolio-det.html, a sub-section of Portfolio. (Look at line 3, you'll see active)
<li class="nav-item"><a class="nav-link" href="index.html">Home</a></li>
<li class="nav-item"><a class="nav-link" href="about-us.html">About</a></li>
<li class="nav-item submenu dropdown active">
<a class="nav-link" href="#">Portfolio</a>
<ul class="dropdown-menu">
<li class="nav-item"><a class="nav-link" href="portfolio.html">Portfolio</a></li>
<li class="nav-item"><a class="nav-link" href="portfolio-det.html">Portrfolio Dets</a>
</ul>
</li>
As you can see
Take a look at this it might help you.
So first you need to get the URL and than match the url with a proper ID to make the menu that you active to be active
<?php
$get_url = $_SERVER['REQUEST_URI'];
?>
<script>
$("#" + '<?php echo $get_url ?>').addClass('active');
</script>
But since you have .html in your url we will want to strip it
$get_url = str_replace(".html", "", $_SERVER['REQUEST_URI']);
So once we have that you need to add id's to your HTML
<li id="about-us" class="nav-item"><a class="nav-link" href="about-us.html">About</a></li>
If you are on the page "portfolio.html" it should light up
Hope this helps or that I at least understood your question correctly
If you are considering using JavaScript, try to detect current link using location.pathname, then go through all the parents and add the active class for nodes that have the nav-item class.
The following solution should do the job.
var url = location.pathname.substr(1), // remove trailing slash
link = document.querySelector('.nav-link[href$="' + url + '"]');
if (link) {
var item = link.parentNode;
while (item.className && (item.nodeName === 'UL' || item.nodeName === 'LI')) {
if (item.className.indexOf('nav-item') > -1) {
item.className += ' active';
}
item = item.parentNode;
}
}
I added below the code how you could use $_SERVER['REQUEST_URI'], this method should work perfectly. The if condition checks if the name index is inside your url.I hope I could help you (It is not an optimal solution but it shows you how you could use it for your specific problem).
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1>Index PHP</h1>
<?php
include 'menu.php';
?>
</body>
</html>
This is the Second.php page.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1>Second PHP</h1>
<?php
include 'menu.php';
echo "Second page!";
?>
</body>
</html>
This is the menu.php which you wanted to include.
<?php
$url = 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
if (strpos($url,'index') !== false) {
echo '<li class="nav-item active"><a class="nav-link" href="index.php">First page</a></li>
<li class="nav-item "><a class="nav-link" href="second.php">Second Page</a></li> ';
} else {
echo ' <li class="nav-item"><a class="nav-link" href="index.php">First page</a></li>
<li class="nav-item active"><a class="nav-link" href="second.php">Second Page</a></li>';
}
?>
<style>
.active{
background-color: green;
}
</style>
You have not defined very important part in your question - how do you "echo" your header.php file?
OP: The entire template is in html only
I ask you this, because usually you cannot just add PHP code in your .html file and expect it to run.
I assume you use standard include/require functions, and that you still run html templates on your server, correct?
Assuming that, you simply have to define an active page variable in your *.html files, for each file a different value of course, and then check in your header.php what the requested page is. You can use that variable's value to adjust other content in the header, as well.
I assume this directory structure:
root
|_ index.html
|_ about-us.html
|_ portfolio.html
|_ portfolio-det.html
|_ header.php
STEP 1: rename all your .html files to .php file extension:
I assume this directory structure:
root
|_ index.php
|_ about-us.php
|_ portfolio.php
|_ portfolio-det.php
|_ header.php
STEP 2: replace all the internal references in navigation links from .html to .php (be careful, triple-check everything!)
STEP 3: define $page variable that will hold a keyword which template you are on. Example code (tested) is below:
index.php
<!DOCTYPE html>
<html>
<head>
<title>INDEX</title>
</head>
<body>
<?php
$page = 'home';
require_once('header.php');
?>
<div>INDEX</div>
</body>
</html>
portfolio.php
<!DOCTYPE html>
<html>
<head>
<title>PORTFOLIO</title>
</head>
<body>
<?php
$page = 'portfolio';
require_once('header.php');
?>
<div>PORTFOLIO</div>
</body>
</html>
portfolio-det.php
<!DOCTYPE html>
<html>
<head>
<title>PORTFOLIO-DET</title>
</head>
<body>
<?php
$page = 'portfolio';
require_once('header.php');
?>
<div>PORTFOLIO-DET</div>
</body>
</html>
header.php
<li class="nav-item <?php if($page == 'home') { echo 'active'; } ?>"><a class="nav-link" href="index.php">Home</a></li>
<li class="nav-item <?php if($page == 'about-us') { echo 'active'; } ?>"><a class="nav-link" href="about-us.php">About</a></li>
<li class="nav-item submenu dropdown <?php if($page == 'portfolio') { echo 'active'; } ?>">
<a class="nav-link" href="#">Portfolio</a>
<ul class="dropdown-menu">
<li class="nav-item"><a class="nav-link" href="portfolio.php">Portfolio</a></li>
<li class="nav-item"><a class="nav-link" href="portfolio-det.php">Portrfolio Dets</a>
</ul>
</li>
I'm attempting to make a template based system to deliver content but I've run into a problem that I just can't seem to solve. When I try to echo out variables that have data from includes it gets outputted in the wrong section of my html.
Below is 'newstuff.php' which is my page to be executed on the browser, the offending variables are $php $head $content.
<?php
$php = include "templates/content/newstuff/phpCode.php";
$head = include "templates/content/newstuff/head.html";
$content = include "templates/content/newstuff/content.php";
include realpath(dirname(__FILE__)).'/templates/templateMain.php';
?>
Below is 'tempalteMain.php' this is my tempalte. Note the location of the echoing of $php $head $content.
<?php
echo $php;
?>
<!DOCTYPE html>
<html>
<head>
<?php echo $head; ?>
</head>
<body class="body1" onload="inputBlur2()">
<div class="borderLine"></div>
<div class="banner"></div>
<div class="mainContent1" >
<div class="header1" >
<div class="headerContainer" >
<ul class="navList1">
<li><a id = "B0" href="index.php">New Stuff</a></li>
<li><a id = "B1" href="MainPage.php">Products</a></li>
<li><a id = "B2" href="ProjectsPage.php">Projects</a></li>
<li><a id = "B3" href="AOrdering.php">About Ordering</a></li>
<li><a id = "B4" href="ContactMe.php">Contact Us</a></li>
<li><a id = "B5" href="FAQPage.php">FAQ</a></li>
<li><a id = "B6" href="SCart.php">My Cart</a></li>
</ul>
</div>
</div>
<div class="content1">
<?php echo $content; ?>
</div>
</div>
</body>
</html>
Below is 'head.html' this provides the code to be delivered by the $head PHP variable.
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="/../StylePR.css">
<title>KickUp Electronics</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
Below is 'content.php' this provides the code to be delivered by the $content PHP variable.
<p>Welcome to the new stuff page!!!</p>
Finally, this is the page source that gets outputted taken from the chrome DOM editor. Note the locations of the information from content.php are wrong and there are strange '1's that are echoed out (also, when viewing the page source, the information from head.html is placed outside the html tags).
<!DOCTYPE html>
<html>
<head><meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="/../StylePR.css">
<title>KickUp Electronics</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
</head>
<body class="body1" onload="inputBlur2()">
<p>Welcome to the new stuff page!!!</p> <!--Wrong Location!-->
1
1
<div class="borderLine"></div>
<div class="banner"></div>
<div class="mainContent1">
<div class="header1">
<div class="headerContainer">
<ul class="navList1">
<li><a id="B0" href="index.php">New Stuff</a></li>
<li><a id="B1" href="MainPage.php">Products</a></li>
<li><a id="B2" href="ProjectsPage.php">Projects</a></li>
<li><a id="B3" href="AOrdering.php">About Ordering</a></li>
<li><a id="B4" href="ContactMe.php">Contact Us</a></li>
<li><a id="B5" href="FAQPage.php">FAQ</a></li>
<li><a id="B6" href="SCart.php">My Cart</a></li>
</ul>
</div>
</div>
<div class="content1">
1 </div>
</div>
</body></html>
I tried searching many times for a solution to no avail. Is this a problem with the echo being executed before the html fully loads? Any help would be highly appreciated!
You're using includes wrong.
$php = include "templates/content/newstuff/phpCode.php";
is immediately outputting the output of that file, and setting $php to 1 (i.e. "it worked!").
Handling Returns: include returns FALSE on failure and raises a warning. Successful includes, unless overridden by the included file, return 1. - http://php.net/manual/en/function.include.php
You can use output buffering to capture the output, but a better solution is probably moving the include calls directly into templateMain.php.
I have a problem with highlighting using php include.
Here's my navigation bar:
<?php
echo '
<link rel="stylesheet" href="css/index-css.css" type="text/css">
<link rel="stylesheet" href="css/bootstrap.min.css">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<div class="container">
<nav class="navbar navbar-inverse">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="/womsy/index.php">Womsy</a>
</div>
<ul class="nav navbar-nav">
<li <?php echo $active[1] ?>Home</li>
<li <?php echo $active[2] ?>Blog</li>
<li <?php echo $active[3] ?>Projects</li>
<li <?php echo $active[4] ?>Contact</li>
<li class="active">About</li>
</ul>
</div>
</nav>';
$active[$current] = "class=active";
?>
I made this with bootstrap, and am trying to highlight via this: http://webdevjunk.com/coding/css/17/php-menu-includes-with-css-style-to-highlight-active-page-link/
<?php
$current = 1;
include 'php/menu.php';
?>
This is what I use on the page, but it doesn't highlight, but when I change the class in the <li> it does work.
Can someone help me figure this out?
function setActive($pageName)
{
if (stripos($_SERVER['REQUEST_URI'], $pageName)) {
echo 'class="active"';
}
}
//$pageName will be home ,blog,projects and contacts
Declare page variable at the very top of each individual page.
Example: <? $page="home";?> goes at top of homepage and <? $page="blog";?> would go on top of blog page, etc.
For each list item in your menu add if statement with corresponding variable and active class.
Example: <ul><li class="<?if($page=="home"){?>active<?}?>"><b>Home</b></li><li class="<?if($page=="blog"){?>active<?}?>"><b>Blog</b></li></ul>
What this does is assign each page a variable. The variable is compared in the if statements in the nav bar to determine which li gets the active class.
This is my first post so forgive as I am just new in the world of web development.
Normally, when I try to make a website, I create a file called header.html and footer.html so that I only change data once in all of the pages rather than having multiple same headers on many html files. And include them all in a php file together with the content and the php codes that comes per page.
Now my problem is because I only have 1 header, the css is designed in a way that whatever the current menu/tab is, it will be marked as "selected" so that its obvious to the user what page they are currently in.
My question is how do I solve this problem:
1.) To have the class="selected" depending on what the current page/url is.
<!--Menu Starts-->
<div class="menu">
<div id="smoothmenu" class="ddsmoothmenu">
<ul>
<li>Home</li>
<li>About </li>
<li>Services </li>
<li>Features</li>
<li>Support
<ul>
<li>Support 1</li>
<li>Support 2</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- Menu Ends--!>
Thank You :)
If you're looking for a non-javascript / php approach...
First you need to determine which nav-link should be set as active and then add the selected class. The code would look something like this
HTML within php file
Call a php function inline within the hyperlink <a> markup passing in the links destination request uri
<ul>
<li><a href="index.php" <?=echoSelectedClassIfRequestMatches("index")?>>Home</a></li>
<li><a href="about.php" <?=echoSelectedClassIfRequestMatches("about")?>>About</a> </li>
<li><a href="services.php" <?=echoSelectedClassIfRequestMatches("services")?>>Services</a> </li>
<li><a href="features.php" <?=echoSelectedClassIfRequestMatches("features")?>>Features</a></li>
<li>Support
<ul>
<li><a href="support1.php" <?=echoSelectedClassIfRequestMatches("support1")?>>Support 1</a></li>
<li><a href="support2.php" <?=echoSelectedClassIfRequestMatches("support2")?>>Support 2</a></li>
</ul>
</li>
</ul>
PHP function
The php function simply needs to compare the passed in request uri and if it matches the current page being rendered output the selected class
<?php
function echoSelectedClassIfRequestMatches($requestUri)
{
$current_file_name = basename($_SERVER['REQUEST_URI'], ".php");
if ($current_file_name == $requestUri)
echo 'class="selected"';
}
?>
You could ID each link and use JavaScript/Jquery to add the selected class to the appropriate link.
<!--Menu Starts-->
<div class="menu">
<div id="smoothmenu" class="ddsmoothmenu">
<ul>
<li id="home-page">Home</li>
<li id="about-page">About </li>
<li id="services-page">Services </li>
<li id="features-page">Features</li>
<li id="support-page">Support
<ul>
<li id="support1-page">Support 1</li>
<li id="support2-page">Support 2</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- Menu Ends--!>
On your content page use jQuery to do something like:
$(document).ready(function(){
$("#features-page").addClass("selected");
});
Another method you could use is:
Add class element based on the name of the page
Give each link a separate id then use jQuery on the individual pages.
<li>Home</li>
<li>About </li>
<li>Services </li>
<li>Features</li>
<li>Support
<ul>
<li>Support 1</li>
<li>Support 2</li>
</ul>
</li>
On the services page:
$(document).ready(function(){
$("#services").addClass("selected");
});
Or even better as robertc pointed out in the comments, there is no need to even bother with the id's just make the jquery this:
$(document).ready(function(){
$("[href='services.php']").addClass("selected");
});
One variant on Chris's approach is to output a particular class to identify the page, for example on the body element, and then use fixed classes on the menu items, and a CSS rule that targets them matching. For example, this page:
<DOCTYPE HTML>
<head>
<title>I'm the about page</title>
<style type="text/css">
.about .about,
.index .index,
.services .services,
.features .features {
font-weight: bold;
}
</style>
</head>
<body class="<?php echo basename(__FILE__, ".php"); ?>">
This is a menu:
<ul>
<li>Home</li>
<li>About </li>
<li>Services </li>
<li>Features</li>
</ul>
</body>
...is pretty light on dynamic code, but should achieve the objective; if you save it as "about.php", then the About link will be bold, but if you save it as "services.php", then the Services link will be bold, etc.
If your code structure suits it, you might be able to simply hardcode the page's body class in the page's template file, rather than using any dynamic code for it. This approach effectively gives you a way of moving the "logic" for the menu system out of the menu code, which will always remain the same for every page, and up to a higher level.
As an added bonus, you can now use pure CSS to target other things based on the page you're on. For example, you could turn all the h1 elements on the index.php page red just using more CSS:
.index h1 { color: red; }
You can do it from simple if and PHP page / basename() function..
<!--Menu Starts-->
<div class="menu">
<div id="smoothmenu" class="ddsmoothmenu">
<ul>
<li><a href="index.php" <?php if (basename($_SERVER['PHP_SELF']) == "index.php") { ?> class="selected" <?php } ?>>Home</a></li>
<li><a href="about.php" <?php if (basename($_SERVER['PHP_SELF']) == "about.php") { ?> class="selected" <?php } ?>>About</a> </li>
<li><a href="services.php" <?php if (basename($_SERVER['PHP_SELF']) == "services.php") { ?> class="selected" <?php } ?>>Services</a> </li>
<li><a href="features.php" <?php if (basename($_SERVER['PHP_SELF']) == "features.php") { ?> class="selected" <?php } ?>>Features</a></li>
</ul>
</div>
</div>
Sorry for my bad English, however may be it could help. You can use jQuery for this task. For this you need to match the page url to the anchor of menu and then add class selected to it. for example the jQuery code would be
jQuery('[href='+currentURL+']').addClass('selected');
I'm new to PHP and HTML, I was creating my first website and I found that I would have to repeat a header over and over so I put it in a 'Header.php' file and included it now I have the problem of checking what page they goto. I need to know what page they goto so I can place a 'class="active"' on the page they goto. I may need the code written for me if it isn't too long. Even an example of how you do it showing all the elements will help. Anyhow heres my code
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>Metamorphosis Design Free Css Templates</title>
<meta name="keywords" content="" />
<meta name="description" content="" />
<input type="hidden" id="link_is_clicked" name="link_is_clicked" value="0"/>
<link href="styles.css" rel="stylesheet" type="text/css" media="screen" />
<link rel="stylesheet" href="nivo-slider.css" type="text/css" media="screen" />
</head>
<body>
<div id="bg_top">
<div id="wrap_bg">
<div id="wrap">
<div id="header">
<div id="menu">
<ul>
<li class="but1_menu">Home</li>
<li class="but2_menu">Blog</li>
<li class="but3_menu">Gallery</li>
<li class="but4_menu">About Us</li>
<li class="but5_menu">Contact Us</li>
</ul>
</div>
<div id="logo">
<h1>metamorph_strongrey</h1>
<small>Small Company Slogan Goes Here</small>
</div>
Thanks for you help.
When it's a small list like you have, I normally would go with a simple if statement:
<li class="but1_menu"><a href="index.php"<?=(($_SERVER['SCRIPT_NAME']=='index.php')?' class="active"':'');?>>Home</a></li>
<li class="but2_menu"><a href="blog.php"<?=(($_SERVER['SCRIPT_NAME']=='blog.php')?' class="active"':'');?>>Blog</a></li>
<li class="but3_menu"><a href="gallery.php"<?=(($_SERVER['SCRIPT_NAME']=='gallery.php')?' class="active"':'');?>>Gallery</a></li>
<li class="but4_menu"><a href="about.php"<?=(($_SERVER['SCRIPT_NAME']=='about.php')?' class="active"':'');?>>About Us</a></li>
<li class="but5_menu"><a href="contact.php"<?=(($_SERVER['SCRIPT_NAME']=='contact.php')?' class="active"':'');?>>Contact Us</a></li>
This will check the current script's name via $_SERVER['SCRIPT_NAME'] and if it matches, it will echo class="active".
First step: Get the current page the user is visiting
$current_url = substr($_SERVER["SCRIPT_NAME"],strrpos($_SERVER["SCRIPT_NAME"],"/")+1);
Second step: Create an array containing all menu link pages
$all_urls = array('index.php', 'blog.php', 'gallery.php', 'about.php', 'contact.php');
Third step: Check if the current url is inside the array. If yes, apply the class
<ul>
<li class="but1_menu"><a href="index.php" <?php if(in_array($current_url, $all_urls)){echo 'class="active"'; } ?>>Home</a></li>
<li class="but2_menu"><a href="blog.php" <?php if(in_array($current_url, $all_urls)){echo 'class="active"'; } ?>>Blog</a></li>
<li class="but3_menu"><a href="gallery.php" <?php if(in_array($current_url, $all_urls)){echo 'class="active"'; } ?>>Gallery</a></li>
<li class="but4_menu"><a href="about.php" <?php if(in_array($current_url, $all_urls)){echo 'class="active"'; } ?>>About Us</a></li>
<li class="but5_menu"><a href="contact.php" <?php if(in_array($current_url, $all_urls)){echo 'class="active"'; } ?>>Contact Us</a></li>
</ul>
All you have to do is place in the href parameter of your anchor tags <a>, a query string indicating what link was pressed.
About Us
Now in your PHP code, you'll want to take a look at the $_GET variable. It is an associative array of all the parameters passed in the URL. So $_GET['action'] will be equal to about.
When you come to write your header once again and want to indicate a "active" link by adding a class, you can just test the action element of the $_GET variable.
Lets assume that in your header file you have an array of links like this -
$headerLinks = array(
'about' => array(
'href'=>'about.php?action=about',
'title'=>'About Us'
),
'home' => array(
'href'=>'home.php?action=home',
'title'=>'Home'
),
'blag' => array(
'href'=>'blag.php?action=blag',
'title'=>'Our Blag'
),
...
);
You would loop over the contents of that array to create your links with the appropriate on having the active class.
foreach($headerLinks AS $key => $link){
$isActive = $_GET['action'] == $key? 'active' : '';
echo ''.$link['title'].'';
}
You should check out this page:
http://php.net/manual/en/reserved.variables.server.php
Specifically the part about REQUEST_URI and that will be what you need. Simply check for this in an if or case statement and apply your class as needed.
You'll only need a few lines of code to check for the uris in your nav bar.
One more method.
Your page will look like
<?php
$curr = "gallery";
include('header.php');
?>
where the $curr variable has a value which could be found in the menu below
and now the menu
<li class="but1_menu"><a <?php echo ($curr == "index" ? "class='active'" : "" ); ?> href="index.php">Home</a></li>
<li class="but2_menu"><a <?php echo ($curr == "blog" ? "class='active'" : "" ); ?> href="blog.php">Blog</a></li>
<li class="but3_menu"><a <?php echo ($curr == "gallery" ? "class='active'" : "" ); ?> href="gallery.php">Gallery</a></li>
<li class="but4_menu"><a <?php echo ($curr == "about_us" ? "class='active'" : "" ); ?> href="about.php">About Us</a></li>
<li class="but5_menu"><a <?php echo ($curr == "contact_us" ? "class='active'" : "" ); ?> href="contact.php">Contact Us</a></li>
To keep code clean is better to use short if/else statement because there is no complex stuff.
Also i recommend to you to put "active" class on <li> but this depends by the style of each developer. In some complex menus it will help you very much.