I have 5 sentence and I want after 3 second the next sentence's background be colored
html:
<div >
<div >
<p > text 1</p>
<p >text 2</p>
<p >text 3</p>
<p >text 4</p>
<p > 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 previous element so I try
document.querySelector(`.text-${count -1}`).classList.add('active')
after count but it dosent work
CodePudding user response:
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 >
<div >
<p >text 1</p>
<p >text 2</p>
<p >text 3</p>
<p >text 4</p>
<p >text 5</p>
</div>
</div>
CodePudding user response:
I refactored JavaScript file a bit:
let count = 1
setInterval(() => {
if (count > 5) {
document.querySelector(`.text-${count- 1}`).classList.remove('active')
count = 1
} else {
document.querySelector(`.text-${count}`).classList.add('active')
if (count > 1) document.querySelector(`.text-${count-1}`).classList.remove('active')
count
}
}, 1000)
.text-wrap p.active {
background-color: #edf0f2;
}
<div >
<div >
<p > text 1</p>
<p >text 2</p>
<p >text 3</p>
<p >text 4</p>
<p > text 5 </p>
</div>
</div>
CodePudding user response:
You need to use remove instead of add to delete the class, and I try to adjust your js code a little bit.
let count = 1;
setInterval((storage) => {
const clsName = 'active';
const current = `.text-${count}`;
const previous = storage.shift();
document.querySelector(previous)?.classList.remove(clsName);
document.querySelector(current).classList.add(clsName);
storage.push(current);
count = count % 5;
count ;
}, 1000, [])
.text-wrap p.active {
background-color: #edf0f2;
}
<div >
<div >
<p > text 1</p>
<p >text 2</p>
<p >text 3</p>
<p >text 4</p>
<p > text 5 </p>
</div>
</div>
