I am trying to make a navigation menu I did all the HTML and CSS when come to javascript I am struck in the middle I am able to add a class to the
I'd personally stick with the document.querySelector
method.
querySelector accepts a CSS like query, which we will use to find an active class on the page. If it exists (the if
statement), remove it and apply the new class on the target.
Please be aware that using className = ""
will result in all classes being removed. It would be more neat to use classList
for everything.
function myFunction(e) {
var el = document.querySelector('.active');
// Check if the element exists to avoid a null syntax error on the removal
if(el) {
el.classList.remove('active');
}
e.target.classList.add('active');
}
you can do like this in pure javascript
function myFunction(e,ev) {
for(var i=0;i<e.children.length;i++)
{
e.children[i].childNodes[0].className = "";
}
ev.target.className = "active";
}
<!DOCTYPE html>
<html>
<head>
<title>Navigation class Toggling</title>
<style type="text/css">
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
header {
width: 100%;
height: auto;
max-width: 600px;
margin: 0 auto;
}
nav {
width: 100%;
height: 40px;
background-color: cornflowerblue;
}
ul {
list-style-type: none;
}
li {
display: inline-block;
}
a {
text-decoration: none;
padding: 8px 15px;
display: block;
text-transform: capitalize;
background-color: darkgray;
color: #fff;
}
a.active {
background-color: cornflowerblue;
}
</style>
</head>
<body>
<header>
<nav>
<ul onclick="myFunction(this,event)">
<li><a href="#">home</a></li>
<li><a href="#">about</a></li>
<li><a href="#">service</a></li>
<li><a href="#">profile</a></li>
<li><a href="#">portfolio</a></li>
<li><a href="#">contact</a></li>
</ul>
</nav>
</header>
<script type="text/javascript">
</script>
</body>
</html>
JS
var targets = document.querySelectorAll('.some-class');
targets.onclick = function(evt) {
evt.classList.toggle('{your-class}');
};
For better browser support:
targets.onclick = function(evt) {
var el = evt.target;
var classes = el.className.split(" ");
var classIndex = classes.indexOf('{your-class}');
if (classIndex >= 0) {
classes.splice(1, classIndex);
} else {
classes.push('{your-clas}');
}
el.className = classes.join(" ");
});