including a css file in html - php

I have this code for a simple dynamic menu and im trying to include a css file:
<?php
// Get current page file name
$page = basename($_SERVER["PHP_SELF"]);
?>
<html>
<head>
<link rel='stylesheet' type='text/css' href='style.css'>
</head>
<body>
<h1>NTUA Library</h1>
<div id="navigation">
<ul>
<li><a href="index.php" <?php if ($page == "index.php") echo 'class="current"' ?>>Products</a></li>
<li><a href="resume.php" <?php if ($page == "resume.php") echo 'class="current"' ?>>Resume</a></li>
<li><a href="photography.php" <?php if ($page == "photography.php") echo 'class="current"' ?>>Photography</a></li>
<li><a href="about.php" <?php if ($page == "about.php") echo 'class="current"' ?>>About</a></li>
<li><a href="contact.php" <?php if ($page == "contact.php") echo 'class="current"' ?>>Contact</a></li>
</ul>
</div>
</body>
This code is inside a file named menu.php in a directory with this path:C:/xampp/htdocs/php-beginner-crud-level-1/
The css file is in the same directory too.
However changing the css code brings no change to the menu.In window's dev options in network tab for the css file there is Status Code: 304 Not Modified.
What am I missing?

Related

How can I determine which page is active/we are on in php

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>

How To Properly Structure php Navigation Bar

I have a index file in my root directory.
I have a directory called pages.
Nav bar is in the includes directory.
If I want to include the navbar in index.php and also in each one of my pages.php which are located in the pages directory. What is the proper way to structure this nav bar so the php can move up and down directories by what page it is on.
each page is identified as
$page = currentPage
And here is my current navbar which is in the includes dir
<ul>
<?php if ($page == 'home') { ?><li class="active">Home</li>
<?php } else { ?><li>Home<?php } ?>
<?php if ($page == 'contact') { ?><li class="active">Contact Us</li>
<?php } else { ?><li>Contact Us<?php } ?>
<?php if ($page == 'services') { ?><li class="active">Services</li>
<?php } else { ?><li>Services<?php } ?>
<?php if ($page == 'employees') { ?><li class="active">Employees</li>
<?php } else { ?><li>Employees<?php } ?>
<?php if ($page == 'dashboard') { ?><li class="active">Dashboard</li>
<?php } else { ?><li>Dashboard<?php } ?>
</ul>
Directory looks like this.
root
root/includes
root/pages
Thanks for your help in advance. I realize I could just do some simple things to get around this but I really want to understand this for the future.
This is how the page is currently laid out:
<?php $page = 'contact'; ?>
<html>
<meta charset="utf-8">
<title>Contact Us</title>
<head>
<base href="http://www.mysite.com/Dir_IM_Working_on_root/pages/" />
<link rel="stylesheet" type="text/css" href="../css/styles.css" />
</head>
<body>
<div id="wrapper">
<div id="nav">
<?php include '../includes/nav.php'; ?>
</div><!-- CLOSING NAV DIV -->
<div id="main">
</div><!-- CLOSING MAIN DIV -->
<footer>
<?php include '../includes/footer.php'; ?>
</footer>
</div><!-- CLOSING WRAPPER DIV -->
</body>
</html>
Easiest would be to output absolute URLs in all cases. (/test.php)
If you want to leave the possibility to run your site in a subfolder, you can prepend all paths with a variable. This can be changed to the current position of your site.
Another way is to add a
<base href="http://www.example.org/subfolder/" />
to your html code and change that accordingly in combination with absolute URLs. All URLs are based on what you put into the attribute. This is a very elegant solution, but it affects a lot, which might be surprising if one is not that trained in web linkage.
I think there is no "right" way. Typo3 uses the base tag variant and it's most likely the way I would use. Lots of other software use the variable variant (or wrap the path in a function -- which is just another way of achieving the same). Just try some ways and decide for the one which seems most appealing to you I'd say.
In my experience the only thing nearly nobody uses are relative URLs.
Update
Use this html in combination with base html tag.
<ul>
<li<?php if ($page == 'home') echo ' class="active' ?>>Home</li>
<li<?php if ($page == 'contact') echo ' class="active' ?>>Contact Us</li>
<li<?php if ($page == 'services') echo ' class="active' ?>>Services</li>
<li<?php if ($page == 'employees') echo ' class="active' ?>>Employees</li>
<li<?php if ($page == 'dashboard') echo ' class="active' ?>>Dashboard</li>
</ul>

How to set current page "active" in php

Hi I have a menu on my site on each page, I want to put it in it's own menu.php file but i'm not sure how to set the class="active" for whatever page i'm on.
Here is my code: please help me
menu.php:
<li class=" has-sub">
<a class="" href="javascript:;"><i class=" icon-time"></i> Zeiten<span class="arrow"></span></a>
<ul class="sub">
<li><a class="" href="offnungszeiten.php">Öffnungszeiten</a></li>
<li><a class="" href="sauna.php">Sauna</a></li>
<li><a class="" href="frauensauna.php">Frauensauna</a></li>
<li class=""><a class="" href="custom.php">Beauty Lounge</a></li>
<li><a class="" href="feiertage.php">Feiertage</a></li>
</ul>
</li>
this method gets the current page using php which will pass a word in this case active and places it inside the class parameter to set the page active.
<?php
function active($currect_page){
$url_array = explode('/', $_SERVER['REQUEST_URI']) ;
$url = end($url_array);
if($currect_page == $url){
echo 'active'; //class name in css
}
}
?>
<ul>
<li><a class="<?php active('page1.php');?>" href="http://localhost/page1.php">page1</a></li>
<li><a class="<?php active('page2.php');?>" href="http://localhost/page2.php">page2</a></li>
<li><a class="<?php active('page3.php');?>" href="http://localhost/page3.php">page3</a></li>
<li><a class="<?php active('page4.php');?>" href="http://localhost/page4.php">page4</a></li>
</ul>
It would be easier if you would build an array of pages in your script and passed it to the view file along with the currently active page:
//index.php or controller
$pages = array();
$pages["offnungszeiten.php"] = "Öffnungszeiten";
$pages["sauna.php"] = "Sauna";
$pages["frauensauna.php"] = "Frauensauna";
$pages["custom.php"] = "Beauty Lounge";
$pages["feiertage.php"] = "Feiertage";
$activePage = "offnungszeiten.php";
//menu.php
<?php foreach($pages as $url=>$title):?>
<li>
<a <?php if($url === $activePage):?>class="active"<?php endif;?> href="<?php echo $url;?>">
<?php echo $title;?>
</a>
</li>
<?php endforeach;?>
With a templating engine like Smarty your menu.php would look even nicer:
//menu.php
{foreach $pages as $url=>$title}
<li>
<a {if $url === $activePage}class="active"{/if} href="{$url}">
{$title}
</a>
</li>
{/foreach}
Create a variable in each of your php file like :
$activePage = "sauna"; (different for each page)
then check that variable in your html page like this
<?php if ($activePage =="sauna") {?>
class="active" <?php } ?>
Put all the below code in menu.php and everything will be taken care of.
// function to get the current page name
function PageName() {
return substr($_SERVER["SCRIPT_NAME"],strrpos($_SERVER["SCRIPT_NAME"],"/")+1);
}
$current_page = PageName();
Use the above to get the current page name then put this in your menu
<li><a class="<?php echo $current_page == 'offnungszeiten.php' ? 'active':NULL ?>" href="offnungszeiten.php">Öffnungszeiten</a></li>
<li><a class="<?php echo $current_page == 'sauna.php' ? 'active':NULL ?>" href="sauna.php">Sauna</a></li>
<li><a class="<?php echo $current_page == 'frauensauna.php' ? 'active':NULL ?>" href="frauensauna.php">Frauensauna</a></li>
<li><a class="<?php echo $current_page == 'custom.php' ? 'active':NULL ?>" href="custom.php">Beauty Lounge</a></li>
<li><a class="<?php echo $current_page == 'feiertage.php' ? 'active':NULL ?>" href="feiertage.php">Feiertage</a></li>
where active is the name of the class which will highlight your menu item
there is two things you can do.
first you can read the current filename of the php file you request by using $_SERVER['PHP_SELF'] or $_SERVER['REQUEST_URI'] or any other $_SERVER global variables that you can use to read your current page and compare it with the link's url, something like this
<a href="offnungszeiten.php" <?php if($_SERVER['PHP_SELF']=='offnungszeiten.php'){ ?>class="activatepage" <?php } ?> >
Öffnungszeiten
</a>
the second one is to create a variable that you can read globally that would store the current name of the current page, like this
<?php
$cur_page ="offnungszeiten"
?>
<a href="offnungszeiten.php" <?php if($cur_page=='offnungszeiten'){ ?>class="activatepage" <?php } ?> >
Öffnungszeiten
</a>
I have done it with php in this way,
function createTopNav($active)
{
$pages = array(
array(
'name'=>'Home',
'link'=>'index'
),
array(
'name'=>'Smartphone',
'link'=>'smartphone'
),
array(
'name'=>'Tablet',
'link'=>'tablet'
),
array(
'name'=>'About Us',
'link'=>'about'
),
array(
'name'=>'Contact Us',
'link'=>'contact'
)
);
$res = "<ul>";
$activePage = "";
foreach($pages as $key=>$val)
{
if($val['link']==$active)
{
$res.= "<li><a href='".$val['link']."' class='active' >".$val['name']."</a></li>";
}
else
{
$res.= "<li><a href='".$val['link']."'>".$val['name']."</a></li>";
}
}
$res.="</ul>";
return $res;
}
And then to call this function
echo createTopNav("about");
and the output will be like this
<ul>
<li>Home</li>
<li>Smartphone</li>
<li>Tablet</li>
<li>About Us</li>
<li>Contact Us</li>
</ul>
I solved this using jQuery/javascript by running the code below each time my any page is loaded:
$(document).ready(function () {
//Get CurrentUrl variable by combining origin with pathname, this ensures that any url appendings (e.g. ?RecordId=100) are removed from the URL
var CurrentUrl = window.location.origin+window.location.pathname;
//Check which menu item is 'active' and adjust apply 'active' class so the item gets highlighted in the menu
//Loop over each <a> element of the NavMenu container
$('#NavMenu a').each(function(Key,Value)
{
//Check if the current url
if(Value['href'] === CurrentUrl)
{
//We have a match, add the 'active' class to the parent item (li element).
$(Value).parent().addClass('active');
}
});
});
This implementation assumes your menu has the 'NavMenu' ID, and uses http://hostname/scriptname.php href attributes like so:
<ul id="NavMenu">
<li>Home</li>
<li>Smartphone</li>
<li>Tablet</li>
<li>About Us</li>
<li>Contact Us</li>
</ul>
Read the javascript comments to see what's going on. If you prefer to use a different href layout (like in your original example), you have to play with the CurrentUrl variable a bit to get it to use the same layout as your href attributes.
For me this was the easiest solution since I had an existing sites with a big menu and many pages, and wanted to avoid having to modify all pages. This allows me to throw in a piece javascript code in the header file (which was a central file already) which solves the problem for all existing pages.
A bit late on the ball, but I just had to solve this myself and ended up using this Javascript method, with a small modification. This has the advantage on not requiring many changes to the current code, just run the script and voila.
window.onload = activateCurrentLink;
function activateCurrentLink(){
var a = document.getElementsByTagName("A");
for(var i=0;i<a.length;i++)
if(a[i].href == window.location.href.split("#")[0])
a[i].className = 'activelink';
}
Send page name in query string and check it on every page by getting the variable.
Simplere solution:
Borrowing the code from asprin above;
Create a new file menu.php where you will store the one and only copy of the menu. In this file, you will create a function addMenu($pageName) that take a parameter as the page name and returns a string consisting of the menu after having added the current tag.
In your HTML code, you would include(menu.php) and then call the function addMenu with the current page name. So your code will look like this:
menu.php
<?php
function addMenu($pageName){
$menu =
'<ul>
<li><a href="Öffnungszeiten.php"' . ($pageName == "Öffnungszeiten" ? "class=\"current\"" : "") . '><span>Öffnungszeiten</span></a></li>
<li><a href="sauna.php"' . ($pageName == "Öffnungszeiten" ? "class=\"current\"" : "") . '><span>Sauna</span></a></li>
<li><a href="frauensauna.php"' . ($pageName == "Frauensauna" ? "class=\"current\"" : "") . '><span>Frauensauna</span></a></li>
<li><a href="custom.php" ' . ($pageName == "lounge" ? "class=\"current\"" : "") . '><span>Beauty Lounge</span></a></li>
<li><a href="Feiertage.php"' . ($pageName == "feiertage" ? "class=\"current\"" : "") . '><span>Feiertage</span></a></li>
</ul>';
return $menu;
}
?>
And in your HTML, say this:
<div id="menu">
<?php
include('menu.php');
echo addMenu("index");
echo $hello;
?>
</div>
This worked for me:
function active_page($script){
$actual = basename($_SERVER['PHP_SELF']);
if($script == $actual){
return 'active-page'; //class name in css
}
}
I have some simple example, see below:
<?php
function active($currect_page) {
$url = $_SERVER['REQUEST_URI'];
if($currect_page == $url){
echo 'active';
}
}
?>
<ul class="navbar-nav mr-auto">
<li class="nav-item <?php active('/');?>">
<a class="nav-link" href="/">Home</a>
</li>
<li class="nav-item <?php active('/other');?>">
<a class="nav-link" href="/other">Other page</a>
</li>
</ul>
Better late than never - I like to keep it simple, to be honest, especially if there's a ton of scripting and PHP going on.
I place this code on the top of each page to identify the page:
<?php
$current_page = 'home';
include 'header.php';
?>
Then your menu/navigation (mine is bootstrap 4) looks like this:
<ul class="navbar-nav mx-auto">
<li class="nav-item <?php if ($current_page=="home") {echo "active"; }?>">
<a class="nav-link" href="<?php echo SITEURL;?>/">Home</a>
</li>
<li class="nav-item <?php if ($current_page=="about") {echo "active"; }?>">
About
</li>
<li class="nav-item <?php if ($current_page=="store") {echo "active"; }?>">
Store
</li>
<li class="nav-item <?php if ($current_page=="news") {echo "active"; }?>">
News
</li>
<li class="nav-item <?php if ($current_page=="contact") {echo "active"; }?>">
Contact
</li>
</ul>
I'm not saying this is the optimal method, but it works for me and it's simple to implement.
adding this:<?= ($activePage == 'home') ? 'active':''; ?> to my link it works perfectly, I only can't make the child of a submenu working to make the parent active.
Assume you have a navbar with the following items:
<ul>
<li id="menu-item-home">HOME</li>
<li id="menu-item-services">SERVICES</li>
<li id="menu-item-about-us">ABOUT US</li>
<li id="menu-item-contact">CONTACT</li>
</ul>
Then, declare a javascript variable in each page as below:
<script>
<?php echo("var active = 'menu-item-home';"); ?>
</script>
The variable "active" is assigned with the corresponding item of each page.
Now, you can use this variable to highlight the active menu item as below.
$(window).ready(function(){$("#" + active).addClass("active");});
I have a similar issue with my web app menu.
I also have sub menus which do not appear as top level menu buttons.
My solution is as follows:
a) Partial php file with menu html and a little php function at the top that checks GET variables against the menu buttons.
I have two GET variables to check: the page and (if necessary) the menu_button.
b) Adding any new php page with a href links to either menu pages or sub menu pages.
The variable "menu_button" is optional and can be used to link to submenu php files.
Of course the security concerning GET variables should be considered.
From my point of view, this solution has less effort than having to maintain an array of pages or links somewhere.
You just use a get variable "menu_button" where you pass the top level menu button that should be marked visually in any link which targets your php file.
Code examples:
Partial menu.php (has to be included in every php file):
<?php
function active($page_link){
$menu_button = $_GET("menu_button") ?: $_GET("page"); // sets the menu button either to the given top level menu or it defaults to the page itself
if($menu_button === $page_link) return "active";
}
?>
<div>
<a href="?page=one" class="<?= active('one') ?>"Link one</a>
Link two
</div>
Any php file with links to sub menu file:
<div>
Link one
Link to sub menu page "three" of menu "two"
</div>
Works for me. Hope someone else can use this.
For making a dynamic active menu link I follow this method.
first, In the menu link, I always use the full address:
//HTML CODE
<ul class="menu">
<li>
Home
</li>
<li>
About us
</li>
<li>
Contact
</li>
</ul>
//Javacript Code
const menus = document.querySelectorAll('.menu li a');
menus.forEach((menu) => {
const currentLocation = window.location.href;
if (currentLocation === window.origin) {
menus[0].classList.add('active');
} else if (menu.href === currentLocation) {
menu.classList.add('active');
} else {
return;
}
});
and then I will use vanilla javascript code to do the rest
You can use
<?php
function active($current_page){
$page = $_GET['p'];
if(isset($page) && $page == $current_page){
echo 'active'; //this is class name in css
}
}
?>
<ul>
<li><a class="<?php active('page1');?>" href="?p=page1">page1</a></li>
<li><a class="<?php active('page2');?>" href="?p=page2">page2</a></li>
<li><a class="<?php active('page3');?>" href="?p=page3">page3</a></li>
<li><a class="<?php active('page4');?>" href="?p=page4">page4</a></li>
</ul>

Checking if a button was clicked and what was clicked

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.

Changing element ID with javascript

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>

Categories