Overview
I have a navbar with li
elements. I add the class active
to the element that corresponds to a variable $page
.
For each of the list elements, I place code similar to this:
<li<?= $page=="new" ? " class='active'" : null ?>><a href="<?= $rootUrl ?>?page=new">New event</a></li>
That way, using this example, if the $page
is "new"
, I add the active
class to the li
element.
This works with top-level list items as well as dropdown children.
Issue
I want the parent element of the dropdown children to also show the active
class when one of its children is active.
To do this with a dropdown with page values "new"
, "existing"
and "gateway"
, I use:
<li class="dropdown<?= $page=="new"||$page=="existing"||$page="gateway" ? " active" : null ?>">
However, this doesn't work; when inspecting the element in the Chrome developer tools, the only class is dropdown1
and any other added classes have disappeared.
Adding the active
class manually in Chrome developer tools produces the correct result.
Full code
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li<?= $page=="dashboard" ? " class='active'" : null ?>><a href="<?= $rootUrl ?>?page=dashboard">Dashboard</a></li>
<li class="dropdown<?= $page=="new"||$page=="existing"||$page="gateway" ? " active" : null ?>">
<a href="javascript:void(0)" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Events <span class="caret"></span></a>
<ul class="dropdown-menu">
<li<?= $page=="new" ? " class='active'" : null ?>><a href="<?= $rootUrl ?>?page=new">New event</a></li>
<li<?= $page=="existing" ? " class='active'" : null ?>><a href="<?= $rootUrl ?>?page=existing">Existing events</a></li>
<li<?= $page=="gateway" ? " class='active'" : null ?>><a href="<?= $rootUrl ?>?page=gateway">Gateway</a></li>
</ul>
</li>
<li><a href="<?= $rootUrl ?>?logout=true">Sign out</a></li>
</ul>
</div>
Question
How can I make the parent element of the dropdown have active
class when one of its child elements has the active
class?