I am kind of confused why my code doesn't work correctly, I hope You will tell me what I've done wrong. I want to highlight navigation tab while clicked.
HTML:
<header class="mainheader">
<!-- Obrazek tutaj-->
<nav>
<ul>
<li><a id="a-home" onclick="dodajAktywne(this)" href="index.html">Home</a></li>
<li><a id="a-omnie" onclick="dodajAktywne(this)" href="omnie.html">O mnie</a></li>
<li><a id="a-kurs" onclick="dodajAktywne(this)" href="kurs.html">Kurs</a></li>
<li><a id="a-kontakt" onclick="dodajAktywne(this)" href="kontakt.html">Kontakt</a></li>
</ul>
</nav>
</header>
JavaScript:
function dodajAktywne(elem) {
var a = document.getElementsByTagName('a')
for (i = 0; i < a.length; i++) {
a[i].classList.remove('active');
}
elem.classList.add('active');
}
CSS:
.active {
color: blue;
background-color: #cf5c3f;
}
You can simplify your JavaScript to:
Fiddle
If you pass the parameter
this
in your HTML to:Note: I've changed
href
attribute to#
, you will have to change it back to your.html
pagesAlternatively, you can do this without JavaScript, using CSS's
:focus
:Fiddle
This code will highlight the navigation tab without needing to include onclick in the HTML, though it doesn't remove the background color if another tab is clicked.
https://codepen.io/mdmcginn/pen/BwrNaj/