I have html file like this:
<ul >
<li ><span>red</span></li>
<li ><span>green</span></li>
<li ><span>blue</span></li>
</ul>
and js like this:
const imagesSlider = () => {
let nextBtn = "";
if ($(".slider-section__toggle-cta").text().length !== 0) {
nextBtn = $(".active").next();
}
if ($(".slider-section__toggle-cta").text().length === 0){
nextBtn = $(".slider-section__toggle-cta:first");
}
console.log($(".active").text().length)
$('.active').removeClass('active');
nextBtn.addClass("active");
}
setInterval(imagesSlider, 3000);
there is one extra condition according to that console.log() that i included in the code, and i don't know how to fix it, so basically when the length is 3 it shows the green, when the length is 5 it shows blue and when the length is 4 it shows nothing!(that's the problem), I want to go back to the first li with "red" text here,
CodePudding user response:
The problem is that you're checking the .slider-section__toggle-cta
text size which is always not empty in the following if
statment.
if ($(".slider-section__toggle-cta").text().length === 0)
Use it this way:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul >
<li ><span>red</span></li>
<li ><span>green</span></li>
<li ><span>blue</span></li>
</ul>
<script type="text/javascript">
const imagesSlider = () => {
let nextBtn = "";
if ($(".active").text().length !== 0) {
nextBtn = $(".active").next();
}
if ($(".active").next().text().length === 0) {
nextBtn = $(".slider-section__toggle-cta:first");
}
console.log($(".active").text().length)
$('.active').removeClass('active');
nextBtn.addClass("active");
}
setInterval(imagesSlider, 3000);
</script>
Look at this demo
CodePudding user response:
i fixed it using
if ($(".active").next().text().length !== 0) {
nextBtn = $(".active").next();
}
if ($(".active").next().text().length === 0) {
nextBtn = $(".slider-section__toggle-cta:first");
}