1

Beginner here. So for my class .active I am setting the order to -1 in my CSS so that it becomes the top div, it removes the class correctly but I am assuming that the order for the previous active is still -1

const divs = document.querySelectorAll('.div');

toggleActive = () =>
{
    if (this.classList.includes("active"))
        this.classList.toggle("active");
    else
    {
        divs.forEach(x => x.classList.remove("active"));
        this.classList.toggle("active");
    }
}

divs.forEach(x => x.addEventListener("click", toggleActive));

Basically I have: div1 div2 div3 div4 div5 and if the user clicks one it should result as div4 div1 div2 div3 div5

click again should result div2 div1 div3 div4 div5 but i get instead div4 div2 div1 div3 div5

CSS:

.active
{
    order: -1;
}
Nmk
  • 1,281
  • 2
  • 14
  • 25
loserslurg
  • 11
  • 1

2 Answers2

0

If you want to continue use your code you need to do this following way.

const divs = document.querySelectorAll('.div');

function toggleActive() {
if (this.classList.contains("active"))
        this.classList.toggle("active");
    else
    {
        divs.forEach(x => x.classList.remove("active"));
        this.classList.toggle("active");
    }
}

divs.forEach(x => x.addEventListener("click", toggleActive));

Explanation:

  1. You can not use an arrow function to bind "this" so you need to use the regular function for that. The reference link, can you bind 'this' in an arrow function

  2. You need to use contains instead of includes.

I have added the code snippet, so that it may help you.

const divs = document.querySelectorAll('.div');

function toggleActive() {
if (this.classList.contains("active"))
        this.classList.toggle("active");
    else
    {
        divs.forEach(x => x.classList.remove("active"));
        this.classList.toggle("active");
    }
}

divs.forEach(x => x.addEventListener("click", toggleActive));
.active
{
    order: -1;
}

div.active{
  color: darkgray;
}
<div class="div">
1. One
</div>
<div class="div">
2. Two
</div>
<div class="div">
3. Three
</div>
Robin Hossain
  • 711
  • 9
  • 12
0

example with data-set which reduces the lines of code and do remember to enclose it within a flex box for the order effect to word

const divs = document.querySelectorAll('[data-index]');

divs.forEach(x=>x.addEventListener('click',()=>{
    divs.forEach(item=>{  
        item.classList=item.dataset.index==x.dataset.index?"div active":"div"
    })
}))
div
{
cursor: pointer;
}

.active
{
    order: -1;
}

div.active{
  color: darkgray;
}
<div style="display: flex;flex-direction: column;">
    <div class="div" data-index="0">
        1. One
    </div>
    <div class="div" data-index="1">
        2. Two
    </div>
    <div class="div" data-index="2">
        3. Three
    </div>
    <div class="div" data-index="3">
        4. Four
    </div>
    <div class="div" data-index="4">
        5. Five
    </div>
</div>
Snivio
  • 1,741
  • 1
  • 17
  • 25