Timo Heckel Timo Heckel - 5 months ago 17
Javascript Question

Highlight current page with ONE sitemap

I hope there is not such a topic, it is kinda hard to search for it.
So my problem:

I have a sitemap.php which is "

<?php include 'sitemap.php'; ?>
" included on every page. Before i made this, i had this sitemap on every single html or php site.

So now: I want to keep this single php file but:
If the user clicks on a link, this site he'll be redirected to should be highlighted now. Short: Highlight the current page but with one sitemap-file.

my css for highlighting:

li.active {
color: #fff;
}


and i guess you all know how a sitemap looks :D

<ul class="nav nav-menu">
<li><a href="channel.php">
<div class="nav-menu__ico"><i class="fa fa-fw fa-comment"></i></div>
<div class="nav-menu__text"><span>Channel</span></div></a></li>
<li><a href="products.html">
<div class="nav-menu__ico"><i class="fa fa-fw fa-users"></i></div>
<div class="nav-menu__text"><span>Groups</span></div></a></li>
<li><a href="groups.php">
<div class="nav-menu__ico"><i class="fa fa-fw fa-bars"></i></div>
<div class="nav-menu__text"><span>Ranking</span></div></a></li>
<li><a href="users.html">
<div class="nav-menu__ico"><i class="fa fa-fw fa-user"></i></div>
<div class="nav-menu__text"><span>Users</span></div></a></li>
</ul>


I guess it have to be done with JS / jQuery / PHP...
But i really dont know how.

Hope someone out there can help me :)!

Sincerely,
Timo

Answer

You can get the url page without heading or trailing part and as soon as the page is ready. Than you can mark your li closest element with the new class:

$(function () {
  var pageUrl = window.location.pathname.split('/').pop();
  $('a[href="' + pageUrl + '"]').closest('li').addClass('active');
});
li.active {
  color: #ffff00;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<ul class="nav nav-menu">
    <li><a href="channel.php">
        <div class="nav-menu__ico"><i class="fa fa-fw fa-comment"></i></div>
        <div class="nav-menu__text"><span>Channel</span></div></a></li>
    <li><a href="products.html">
        <div class="nav-menu__ico"><i class="fa fa-fw fa-users"></i></div>
        <div class="nav-menu__text"><span>Groups</span></div></a></li>
    <li><a href="groups.php">
        <div class="nav-menu__ico"><i class="fa fa-fw fa-bars"></i></div>
        <div class="nav-menu__text"><span>Ranking</span></div></a></li>
    <li><a href="users.html">
        <div class="nav-menu__ico"><i class="fa fa-fw fa-user"></i></div>
        <div class="nav-menu__text"><span>Users</span></div></a></li>
</ul>

Comments