So I have a menu with different items
<div class="right-nav">
<a href="/metrics/website/index" class="active">Home</a>
<a href="/metrics/website/pages/archives">Archives</a>
</div>
The class="active"
highlights the menu item, and I was wondering how I could make this class change depending on which page I was on. So if the user visited Archives
, then that has class="active"
.
The class is just a simple color
.topnav a.active {
/* When a-tags inside this class has been clicked - do highlight*/
color: var(--selected-nav-page);
}
All my html code is run inside php files.
UPDATE
Might have found something that works, using php, what do you guys think?
Made a php
script which checks what page I’m on, and writes active or not in my a-tags.
<?php
function active($currect_page){
$url = str_replace(".php", "", basename($_SERVER['PHP_SELF'])); //name without .php
if($currect_page == $url){
echo 'active'; //class name in css
}
}
?>
<div class="right-nav">
<a href="#index" class="<?php active('index'); ?> active">Home</a>
<a href="#archives" class="<?php active('archives'); ?>">Archives</a>
</div>
Advertisement
Answer
Since I dont use the .php
on my pages, I remove that part from the filename. Beside that I use the basename of PHP_SELF, to get the name of the current file. If that is equal to the name in the menu function, then write active. Only problem here would be if I had two files with same name in different directories, and added them to the menu. Because then both would be highlighted, which is why I added basename(getcwd())
, to get the parent directory, then also includes that the function should be called with it’s parent name like active('website/index')
<?php
function active($currect_page){
$url = basename(getcwd())."/".str_replace(".php", "", basename($_SERVER['PHP_SELF']));
//If filename is just "name" or "name.php"
//Also checks which directory the file is in, to avoid highlighting multiple menu items with same name
//$currect_page == $url :: parentFolder/fileName == parentFolder/fileName (without .php here)
if($currect_page == $url || $currect_page == basename(getcwd())."/".basename($_SERVER['PHP_SELF'])){
echo 'active'; //class name in css
}
}
?>
<div class="right-nav">
<a href="/metrics/website/index" class="<?php active('website/index'); ?>">Home</a>
<a href="/metrics/website/pages/archives" class="<?php active('pages/archives'); ?>">Archives</a>
</div>