set active element background red and set the remaining elements to white backgrounnd using vanilla js

Issue

I have a simple section that contains five elements on default the first element background is red (active element) now I want when u click any of the remaining elements to change the background color to red, and the remaining elements to have white background color using vanilla js.

Problem: When I click any of the remaining elements is set to red but the previous active element is still red; live demo

My solution

HTML

<div id="panels">
  <div class="panel active">First</div>
  <div class="panel">second</div> 
  <div class="panel">third</div>  
  <div class="panel">fouth</div>  
  <div class="panel">Fith</div>
</div>

CSS

#panels{
display: flex;
justify: space-between;
align-items: center
}

.panel{
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100px;
    height: 100px;
    background: white;
    color: black;
    font-size: 24px;
    text-align: center;
    margin: 0px auto;
    cursor: pointer;
}
.active{
  background: red;
}

Js

 var panel = document.getElementById('panels'); // Parent

        panel.addEventListener('click', function (e) {
            var target = e.target; // Clicked element
            while (target && target.parentNode !== panel) {
                target = target.parentNode; // If the clicked element isn't a direct child
                if (!target) { return; } // If element doesn't exist
            }
            if (target.tagName === 'DIV') {
                target.classList.toggle('active');

            } else {
                console.log('love')

            }
        });

What do I need to change here to get this working?

Solution

var panels = document.querySelectorAll("#panels > .panel")
panels.forEach(each=>{
    each.onclick = function(){
        panels.forEach(ss=>ss.classList.remove("active")) // removing active from all
        each.classList.add("active") // assigning active to selected
    }
})
.panel{
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100px;
    height: 100px;
    background: white;
    color: black;
    font-size: 24px;
    text-align: center;
    margin: 0px auto;
    cursor: pointer;
}
.active{
  background: red;
}
<div id="panels">
  <div class="panel active">First</div>
  <div class="panel">second</div> 
  <div class="panel">third</div>  
  <div class="panel">fouth</div>  
  <div class="panel">Fith</div>
</div>

Answered By – Amir Rahman

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published