I have a simple menu in HTML:
<ul id="menu">
<li><a id="admin" onclick="changeActive('admin');" class="active a red">Admin</a></li>
<li><a id="dash" onclick="changeActive('dash');" class="a black">Dash</a></li>
<li><a id="notifs" onclick="changeActive('notifs');" class="a black">Notifs</a></li>
</ul>
The idea is to change the active element dynamically.
My current function is:
function changeActive(id)
{
document.getElementById(id).className += "active a red";
var c = document.querySelectorAll("ul a");
for (i in c)
{
fav = c[i].attributes[0];
if(fav.value!=id)
{
console.log(fav.value);
document.getElementById(fav.value).className += "a black";
}
}
}
Is there a more efficient solution to this? Thanks!
Notice I removed +=
so that you donot end up adding same class every time.
function changeActive(id) {
var c = document.querySelectorAll("ul a");
var i;
for (i in c) {
c[i].className = 'a black';
}
//update it at last
document.getElementById(id).className = "active a red";
}
Use classList
property and it's add
method.
remove
will remove the class
document.getElementById(id).classList.add("active a red");
With navmenus, you want to set the active state on the li and apply the style to the a within the active li.
The following has both the id, the active class and the onclick handler in the li ( as well as a fake href in the a) and functions to remove the active class from all li's on the click and then apply it to the selected li. The .active class CSS then colors the a in red.
function changeActive(option){
var option = option;
var li = document.getElementsByTagName("li");
for(i=0;i<li.length;i++){
li[i].classList.remove("active");
}
document.getElementById(option).classList.add("active");
}
ul{list-style:none}
a{color:black;text-decoration:none}
.active a{color:red}
<ul id="menu">
<li class="active" onclick="changeActive('admin')" id="admin"><a href="#">Admin</a></li>
<li onclick="changeActive('dash')" id="dash"><a href="#">Dash</a></li>
<li onclick="changeActive('notifs')" id="notifs"><a href="#">Notifs</a></li>
</ul>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With