I apparently have no idea of how to add class="current" to the <li> tag
of the parent menu when it's <li> tag
has a class="active"
. I tried using jQuery to implement this, but It does not work since the page is reloaded when clicking on it. So I simply added a field called name
into the database to use as a parameter. Bellowing is my PHP code:
echo '<ul>';
$main_menu = model::getMainMenu();
foreach($main_menus as $menu){
echo '<li class="dropdown">
<a href=?page='.$menu['name'].'&m=1 class='.(($_GET['page'] == $menu['name'])?'current':'').'>'.$menu['title'].'</a>';
$sub_menus = model::getSubMenu($menu['id']);
if( $sub_menus != '' ){
echo '<ul>';
foreach($sub_menus as $sub){
echo '<li><a href=?page='.$sub['name'].' class='.(($_GET['page']==$sub['name'])?'current':'').'>'.ucwords( $sub['title'] ).'</a></li>';
}
echo '</ul>';
}
echo '</li>';
}
</ul>
I can only detect which sub page or page is currently active by comparing the $_GET['page'] and the $sub['name']
(my url structure is simply like this index.php?page=home
). However, I have no idea how to detect the parent menu when its child is currently selected.
I uploaded the page here
See code below. Not sure if it is completely correct, but idea should be clear from it. Basically - you can collect all LIs html into a variable and set a flag to tru if one of LIs is active. And than echo everything taking into account flag variable state.
echo '<ul>';
$main_menu = model::getMainMenu();
foreach($main_menus as $menu) {
$sub_menus = model::getSubMenu($menu['id']);
$lis = "";
$hasCurrent = false;
if($sub_menus != '') {
foreach($sub_menus as $sub) {
$lis .= '<li><a href=?page='.$sub['name'].' class='.(($_GET['page']==$sub['name'])?'current':'').'>'.ucwords( $sub['title'] ).'</a></li>';
if($_GET['page']==$sub['name']) {
$hasCurrent = true;
}
}
echo '<li class="dropdown ' . $hasCurrent ? 'active' : '' . '">
<a href=?page='.$menu['name'].'&m=1 class='.(($_GET['page'] == $menu['name'])?'current':'').'>'.$menu['title'].'</a>';
if($lis != '') {
echo '<ul>';
echo $lis;
echo '</ul>';
}
}
echo '</li>';
}
</ul>
One possible solution:
Give the 'active' tag an ID, rather than a class - as only one page can be active at a time (presumably).
Then use Javascript to walk through the DOM and find the parent element:
var active_elem = document.getElementById("active");
var parent_element = active_elem.parentElement.parentElement;
Then assign the class / ID or whatever it is you want to do.