I try to make a menu that adds the green color to the selected one and in turn deselects the others by adding the white color, that works from top to bottom and vice versa, I already tried to program it but it doesn’t seem to work well, could you tell me where my error is.
when clicking on any of the menu fields, I want it to select the menu field that I clicked on and paint it green and deselect the others by painting them white.
This functionality must work from top to bottom (from the Home field to the about field of the menu) and from bottom to top (from the about field to the Home of the menu ), that is, in any direction that is clicked.
my source code is:
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
</style>
</head>
<body>
<div class="container">
<p class="menu">Home</p>
<p class="menu">Gallery</p>
<p class="menu">Technology</p>
<p class="menu">Information</p>
<p class="menu">Contact</p>
<p class="menu">About</p>
</div>
<script>
let menu = document.querySelectorAll('.menu');
menu.forEach((btn, i) => {
btn.addEventListener("click", (ev) =>{
//console.log(ev.target);
// clicking from top to bottom or from home to about
for(let bt = 0; bt < i; bt++){
menu[bt].style.background = '#FFFFFF';
}
//missing make the condition, when home is clicked, the selection or the green color should be removed, from the about menu.
//----------------------------------------------
// clicking from bottom to top or from about to home
// it seems, it doesn't work, where is my mistake?
for(let at = menu.length; at > i; at--){
menu[i].style.background = '#FFFFFF';
}
menu[i].style.background = '#BEFFC7';
});
});
</script>
</body>
</html> ```
3
Answers
This solution is using two for but I think it would be the same using forEach.
here is the solution using a forEach
There is no need to repaint all menu items each time a single item gets ‘clicked’:
menu
items white by default.menu
item clicked green (or white when it was already green)..menu
item green on hover.snippet