I want to to add a “active” Class to the navigation element from the current page. It works fine except for the index page, I want to keep the a href=”/” Link for the index site, because of SEO and aesthetics.
Any help?
$(function() {
var pgurl = window.location.href.substr(window.location.href.lastIndexOf("/") + 1);
$(".menu-side a").each(function() {
if ($(this).attr("href") == pgurl || $(this).attr("href") == '')
$(this).addClass("active");
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<nav class="menu-side">
<a title="Startseite" href="/">Startseite</a>
<a title="Über Mich" href="ueber_mich.html">Über Mich</a>
<a title="Projekte" href="projekte.html">Projekte</a>
<a title="Galerie" href="galerie.html">Galerie</a>
<a title="Kontakt" href="kontakt.html">Kontakt</a>
<a title="Impressum" href="impressum.html">Impressum</a>
</nav>
2
Answers
You can always check if an active class is set, and if not, set the default one:
You can use
sessionStorage
to save thehref
of the element clicked, and when the page redirects, you reapply the class to the element with the savedhref
like so:Here is the JSFiddle of the code