Home > other >  How to loop a toggle classList infinitely through an array?
How to loop a toggle classList infinitely through an array?

Time:06-27

I'm trying to get a cycle/loop effect on 3 H1 elements, displaying a purple font color for each H1 for some seconds and then change to another H1 right below the first one.

I wanted this effect to be infinite and I thought about using for loop and setInterval but I'm getting anywhere.

setInterval(changeColorLoop(), 2000);

function changeColorLoop() {
  const titleArtArray = document.querySelectorAll(".art-text");

  for (var i = 0; i < titleArtArray.length; i  ) {
    titleArtArray[i].classList.toggle = ".purple";
  }
}



  <div >
                <h1 >Think</h1>
                <h1 >Design</h1>
                <h1 >Code</h1>
              </div>


.purple {
  color: purple;
}

CodePudding user response:

This gets the "animation" going. Needs a little polishing. Edit: Polished, thanks to @jeanjacquesgourdin. Edit 2: Added some CSS transition

let index = 0;

function changeColorLoop() {
  const titleArtArray = document.querySelectorAll(".art-text");

  titleArtArray[index % 3].classList.toggle("purple");
  titleArtArray[(index   1) % 3].classList.toggle("purple");
  index  
}

setInterval(changeColorLoop, 1000);
.art-text {
  transition: all 1000ms ease-in-out;
}

.purple {
  color: purple;
}
<div >
  <h1 >Think</h1>
  <h1 >Design</h1>
  <h1 >Code</h1>
</div>

CodePudding user response:

If I understand well you can do something like

let index = 0;
const titleArtArray = document.querySelectorAll(".art-text");

setInterval(()=>{
  titleArtArray[index].classList.toggle = ".purple";
  titleArtArray[index 1].classList.toggle = ".purple";
  index = (index   1) % 3
}, 2000);

  <div >
    <h1 >Think</h1>
    <h1 >Design</h1>
    <h1 >Code</h1>
  </div>

CodePudding user response:

You can do following:

 <script>
  setInterval(() => {
    const titleArtArray = document.querySelectorAll(".art-text");
    titleArtArray[0].classList.add("purple");
    setTimeout(() => {
      titleArtArray[0].classList.remove("purple");
      titleArtArray[1].classList.add("purple");
      setTimeout(() => {
        titleArtArray[1].classList.remove("purple");
      titleArtArray[2].classList.add("purple");
      setTimeout(() => {
        titleArtArray[2].classList.remove("purple");
      }, 500);
    }, 500);
  }, 500);
}, 2000);
  
</script>
<div >
  <h1 >Think</h1>
  <h1 >Design</h1>
  <h1 >Code</h1>
</div>
<style>
  .purple {
    color: purple;
  }
</style>
  • Related