Skip to content
Advertisement

autoplay hover after 3 second

I have 5 sentences and I want after 3 seconds the next sentence’s background to be colored

HTML:

    <div class="text-slider">
        <div class="text-wrap">
            <p class="text text-1 active"> text 1</p>
            <p class="text text-2">text 2</p>
            <p class=" text text-3">text 3</p>
            <p class="text text-4">text 4</p>
            <p class="text text-5"> text 5 </p>
        </div>
    </div>

CSS:

.text-wrap p.active {
  background-color: #edf0f2;
}

JS

let count = 1
setInterval(()=>{

    document.querySelector(`.text-${count}`).classList.add('active')
    count++
   
    if(count>5){
        count =1
    }
}, 3000)

I want to remove class active from the previous element so I try

 document.querySelector(`.text-${count -1}`).classList.remove('active')

after count++ but it doesn’t work

Advertisement

Answer

Instead of finding an element with relative to the count, you can hack it a bit, and in your selector find active element and remove that active class from it as follows.

let count = 1;
setInterval(() => {
  // Here you remove active class from `p` tag which had it
  document.querySelector(".text.active").classList.remove("active"); // <- HERE
  
  document.querySelector(`.text-${count}`).classList.add("active");
  count++;

  if (count > 5) {
    count = 1;
  }
}, 3000);

Snippet

let count = 1;
setInterval(() => {
  document.querySelector(".text.active").classList.remove("active");
  document.querySelector(`.text-${count}`).classList.add("active");
  count++;

  if (count > 5) {
    count = 1;
  }
}, 1000);
.text-wrap p.active {
  background-color: #edf0f2;
}
<div class="text-slider">
    <div class="text-wrap">
      <p class="text text-1 active">text 1</p>
      <p class="text text-2">text 2</p>
      <p class="text text-3">text 3</p>
      <p class="text text-4">text 4</p>
      <p class="text text-5">text 5</p>
    </div>
</div>
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement