Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
34
rated 0 times [  36] [ 2]  / answers: 1 / hits: 104543  / 10 Years ago, sun, november 16, 2014, 12:00:00

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;
}

More From » html

 Answers
110

You can simplify your JavaScript to:



Fiddle



function dodajAktywne(elem) {
// get all 'a' elements
var a = document.getElementsByTagName('a');
// loop through all 'a' elements
for (i = 0; i < a.length; i++) {
// Remove the class 'active' if it exists
a[i].classList.remove('active')
}
// add 'active' classs to the element that was clicked
elem.classList.add('active');
}


If you pass the parameter this in your HTML to:



<header class=mainheader>
<!-- Obrazek tutaj-->
<nav>
<ul>
<li><a id=a-home onclick=dodajAktywne(this) href=#>Home</a>
</li>
<li><a id=a-omnie onclick=dodajAktywne(this) href=#>O mnie</a>
</li>
<li><a id=a-kurs onclick=dodajAktywne(this) href=#>Kurs</a>
</li>
<li><a id=a-kontakt onclick=dodajAktywne(this) href=#>Kontakt</a>
</li>
</ul>
</nav>
</header>


Note: I've changed href attribute to #, you will have to change it back to your .html pages






Alternatively, you can do this without JavaScript, using CSS's :focus:



Fiddle



a:focus {
color: blue;
background-color: #cf5c3f;
}

[#68791] Thursday, November 13, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
wilson

Total Points: 27
Total Questions: 93
Total Answers: 93

Location: Tajikistan
Member since Sun, Aug 29, 2021
3 Years ago
wilson questions
Tue, Aug 9, 22, 00:00, 2 Years ago
Wed, May 11, 22, 00:00, 2 Years ago
Wed, May 20, 20, 00:00, 4 Years ago
Wed, May 13, 20, 00:00, 4 Years ago
;