This is a slideshow HTML that’s generated with 3 images and shown are the Prev <<
and Next >>
buttons.
<div class="wp-block-gallery">
<div class="wpcookie-slide">
<img decoding="async" loading="lazy" src="image1.jpg" alt="image">
</div>
<div class="wpcookie-slide">
<img decoding="async" loading="lazy" src="image2.jpg" alt="image">
</div>
<div class="wpcookie-slide">
<img decoding="async" loading="lazy" src="image3.jpg" alt="image">
</div>
<span class="wpcookie-controls wpcookie-left-arrow"> << Prev </span>
<span class="wpcookie-controls wpcookie-right-arrow"> Next >> </span>
</div>
I want to hide the << Prev
& Next >>
buttons when there’s just 1 image in the slideshow. It creates a bad UX for the users to show the arrows when there’s only 1 image in the slideshow.
Here’s the JS code that generates the slideshow:
document.querySelectorAll(".wp-block-gallery")?.forEach( slider => {
var src = [];
var alt = [];
var img = slider.querySelectorAll("img");
img.forEach( e => { src.push(e.src); if (e.alt) { alt.push(e.alt); } else { alt.push("image"); } })
let i = 0;
let image = "";
let myDot = "";
src.forEach ( e => { image = image + `<div class="wpcookie-slide" > <img decoding="async" loading="lazy" src="${src[i]}" alt="${alt[i]}" > </div>`; i++ })
i = 0;
src.forEach ( e => { myDot = myDot + `<span class="wp-dot"></span>`; i++ })
let dotDisply = "none";
if (slider.classList.contains("dot")) dotDisply = "block";
const main = `<div class="wp-block-gallery">${image}<span class="wpcookie-controls wpcookie-left-arrow"> << Prev </span> <span class="wpcookie-controls wpcookie-right-arrow"> Next >> </span></div> `
slider.insertAdjacentHTML("afterend",main );
slider.remove();
})
document.querySelectorAll(".wp-block-gallery")?.forEach( slider => {
var slides = slider.querySelectorAll(".wpcookie-slide");
var dots = slider.querySelectorAll(".wp-dot");
var index = 0;
slider.addEventListener("click", e => {if(e.target.classList.contains("wpcookie-left-arrow")) { prevSlide(-1)} } )
slider.addEventListener("click", e => {if(e.target.classList.contains("wpcookie-right-arrow")) { nextSlide(1)} } )
function prevSlide(n){
index+=n;
console.log("prevSlide is called");
changeSlide();
}
function nextSlide(n){
index+=n;
changeSlide();
}
changeSlide();
function changeSlide(){
if(index>slides.length-1)
index=0;
if(index<0)
index=slides.length-1;
for(let i=0;i<slides.length;i++){
slides[i].style.display = "none";
dots[i].classList.remove("wpcookie-slider-active");
}
slides[index].style.display = "block";
dots[index].classList.add("wpcookie-slider-active");
}
})