'slider shows one extra condition in jquery
I have html file like this:
<ul class="slider-section__toggle-ctas">
<li class="slider-section__toggle-cta active"><span>red</span></li>
<li class="slider-section__toggle-cta"><span>green</span></li>
<li class="slider-section__toggle-cta"><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,
Solution 1:[1]
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 class="slider-section__toggle-ctas">
<li class="slider-section__toggle-cta active"><span>red</span></li>
<li class="slider-section__toggle-cta"><span>green</span></li>
<li class="slider-section__toggle-cta"><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
Solution 2:[2]
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");
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Afra |
