how to add dynamic href to vanilla slider in which slides set background image data?

  carousel, html, javascript, user-interface

I built a custom vanilla image slider today and realized after the fact that each slide is supposed to be able to link to a different page. I tried to add each link as a data attribute (I thought I was coding in react for a second and treated it like a prop.. whoops) but then the links pushed into the slideArray and broke the carousel since it is trying to set it (the href) as a background image. What would be the best way for me to add a custom link to each slide (both accessibility-wise and convenience-wise) without having to recode the entire slider? This slider is currently working perfectly && is responsive so I don’t want to redo the whole thing.

<div class="slider">
<div class="slide" data-background="https://picsum.photos/825/400"></div>
<div class="slide" data-background="https://picsum.photos/800/400"></div>
<div class="slide" data-background="https://picsum.photos/850/400"></div>
<div class="slide" data-background="https://picsum.photos/900/450"></div>
<a id="prev" class="control prev"></a>
<a id="next" class="control next"></a>
</div>
<a class="link">
</a>
<div class="slider"><a class="link">
<div class="slide" data-background="https://picsum.photos/825/400"></div>
<div class="slide" data-background="https://picsum.photos/800/400"></div>
<div class="slide" data-background="https://picsum.photos/850/400"></div>
<div class="slide" data-background="https://picsum.photos/900/450"></div>
</a><a id="prev" class="control prev"></a>
<a id="next" class="control next"></a>
</div>
<script>
const next = document.querySelector("#next");
const prev = document.querySelector("#prev");
const slideArray = [];
for (let i = 0; i < document.querySelectorAll('.slider div').length; i++) {
    slideArray.push(document.querySelectorAll('.slider div')[i].dataset.background);  //fill slide array with slider div nodes
}
console.log(slideArray)

let currentSlideIndex = -1;
function advanceSliderItem() {
    currentSlideIndex++;
    if (currentSlideIndex >= slideArray.length) {
        currentSlideIndex = 0;
    }
  document.querySelector('.slider').style.cssText = 'background: url("' + slideArray[currentSlideIndex] + '") no-repeat center center; background-size: cover;';
    }

function previousSliderItem() {
    currentSlideIndex--;
    if (currentSlideIndex <= -1) {
        currentSlideIndex =  slideArray.length - 1;
    }
  document.querySelector('.slider').style.cssText = 'background: url("' + slideArray[currentSlideIndex] + '") no-repeat center center; background-size: cover;';
    }

next.addEventListener("click", advanceSliderItem )
prev.addEventListener("click", previousSliderItem )

    let intervalID = setInterval(advanceSliderItem, 5000);
    advanceSliderItem()
</script>

Source: Ask Javascript Questions

LEAVE A COMMENT